Qual è l'ultimo codice postale e zip regex?


201

Sto cercando l'ultimo codice postale e regex codice postale. Sto cercando qualcosa che coprirà la maggior parte (si spera tutto) del mondo.


4
Un unico regex per tutti i codici postali sarebbe inutile nella maggior parte dei casi, per non parlare del fatto che richiede molta codifica Unicode. Molto meglio è controllare regex su base paese per paese in modo da non convalidare cose come "New York, NY AF23Q" nel modo corretto.
Sì, quel Jake.

101
You have a problem. You write a regex for it. Now you have two problems.
Robert S.


2
The one that handles all possible future values.
Jodrell

Risposte:


127

There is none.

I codici postali / postali in tutto il mondo non seguono un modello comune. In alcuni paesi sono costituiti da numeri, in altri possono essere combinazioni di numeri e lettere, alcuni possono contenere spazi, altri punti, il numero di caratteri può variare da due ad almeno sei ...

Quello che potresti fare (teoricamente) è creare una regex separata per ogni paese del mondo, non raccomandabile IMO. Ma ti mancherebbe ancora nella parte di convalida: il codice postale 12345potrebbe esistere, ma 12346forse 12344non esiste neanche. Come lo controlli con una regex?

Non puoi.


I suspect that a regex could be compiled, but that a task like this be much better suited to a database. The regex would look something like 10000|10001|10002|10003|.......
Kibbee


You can use a regexp first that matches your country (see en.wikipedia.org/wiki/List_of_postal_codes) and do a real check by an external service like geonames.org/export/ws-overview.html
SimonSimCity

3
I miei due centesimi: in Brasile sono in realtà 8 numeri, 5 seguiti da un trattino e altri 3
Jorge Campos,

^\d{5}(?:[-\s]\d{4})?$
Aamir Afridi

261

Il CLDR unicode contiene il regex del codice postale per ciascun paese. (158 regex in totale!)

Google ha anche un servizio web con informazioni sulla formattazione dell'indirizzo per paese, inclusi i codici postali, qui - http://i18napis.appspot.com/address (ho trovato quel link tramite http://unicode.org/review/pri180/ )

modificare

Ecco una copia di regex PostalCodeData.xml :

"GB", "GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|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[A-Z]{2}[ ]?[A-Z0-9]{2}"
"BA", "\d{5}"
"IO", "BBND 1ZZ"
"BN", "[A-Z]{2}[ ]?\d{4}"
"BG", "\d{4}"
"KH", "\d{5}"
"CV", "\d{4}"
"CL", "\d{7}"
"CR", "\d{4,5}|\d{3}-\d{4}"
"HR", "\d{5}"
"CY", "\d{4}"
"CZ", "\d{3}[ ]?\d{2}"
"DO", "\d{5}"
"EC", "([A-Z]\d{4}[A-Z]|(?:[A-Z]{2})?\d{6})?"
"EG", "\d{5}"
"EE", "\d{5}"
"FO", "\d{3}"
"GE", "\d{4}"
"GR", "\d{3}[ ]?\d{2}"
"GL", "39\d{2}"
"GT", "\d{5}"
"HT", "\d{4}"
"HN", "(?:\d{5})?"
"HU", "\d{4}"
"IS", "\d{3}"
"IN", "\d{6}"
"ID", "\d{5}"
"IL", "\d{5}"
"JO", "\d{5}"
"KZ", "\d{6}"
"KE", "\d{5}"
"KW", "\d{5}"
"LA", "\d{5}"
"LV", "\d{4}"
"LB", "(\d{4}([ ]?\d{4})?)?"
"LI", "(948[5-9])|(949[0-7])"
"LT", "\d{5}"
"LU", "\d{4}"
"MK", "\d{4}"
"MY", "\d{5}"
"MV", "\d{5}"
"MT", "[A-Z]{3}[ ]?\d{2,4}"
"MU", "(\d{3}[A-Z]{2}\d{3})?"
"MX", "\d{5}"
"MD", "\d{4}"
"MC", "980\d{2}"
"MA", "\d{5}"
"NP", "\d{5}"
"NZ", "\d{4}"
"NI", "((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?"
"NG", "(\d{6})?"
"OM", "(PC )?\d{3}"
"PK", "\d{5}"
"PY", "\d{4}"
"PH", "\d{4}"
"PL", "\d{2}-\d{3}"
"PR", "00[679]\d{2}([ \-]\d{4})?"
"RO", "\d{6}"
"RU", "\d{6}"
"SM", "4789\d"
"SA", "\d{5}"
"SN", "\d{5}"
"SK", "\d{3}[ ]?\d{2}"
"SI", "\d{4}"
"ZA", "\d{4}"
"LK", "\d{5}"
"TJ", "\d{6}"
"TH", "\d{5}"
"TN", "\d{4}"
"TR", "\d{5}"
"TM", "\d{6}"
"UA", "\d{5}"
"UY", "\d{5}"
"UZ", "\d{6}"
"VA", "00120"
"VE", "\d{4}"
"ZM", "\d{5}"
"AS", "96799"
"CC", "6799"
"CK", "\d{4}"
"RS", "\d{6}"
"ME", "8\d{4}"
"CS", "\d{5}"
"YU", "\d{5}"
"CX", "6798"
"ET", "\d{4}"
"FK", "FIQQ 1ZZ"
"NF", "2899"
"FM", "(9694[1-4])([ \-]\d{4})?"
"GF", "9[78]3\d{2}"
"GN", "\d{3}"
"GP", "9[78][01]\d{2}"
"GS", "SIQQ 1ZZ"
"GU", "969[123]\d([ \-]\d{4})?"
"GW", "\d{4}"
"HM", "\d{4}"
"IQ", "\d{5}"
"KG", "\d{6}"
"LR", "\d{4}"
"LS", "\d{3}"
"MG", "\d{3}"
"MH", "969[67]\d([ \-]\d{4})?"
"MN", "\d{6}"
"MP", "9695[012]([ \-]\d{4})?"
"MQ", "9[78]2\d{2}"
"NC", "988\d{2}"
"NE", "\d{4}"
"VI", "008(([0-4]\d)|(5[01]))([ \-]\d{4})?"
"PF", "987\d{2}"
"PG", "\d{3}"
"PM", "9[78]5\d{2}"
"PN", "PCRN 1ZZ"
"PW", "96940"
"RE", "9[78]4\d{2}"
"SH", "(ASCN|STHL) 1ZZ"
"SJ", "\d{4}"
"SO", "\d{5}"
"SZ", "[HLMS]\d{3}"
"TC", "TKCA 1ZZ"
"WF", "986\d{2}"
"XK", "\d{5}"
"YT", "976\d{2}"

3
Solo con una rapida scansione del codice postale AU-regex ... questo regex è molto semplice e consentirà molti falsi positivi, quindi non è esaustivo.
Taryn East,

7
L'ultima versione del CLDR unicode contenente il regex del codice postale è la versione 26.0.1. Nelle versioni successive è stato rimosso perché i dati non sono stati mantenuti e non è stato possibile trovare altre fonti affidabili.
Software KIKO,

1
Lo stesso, molto semplice per regex codice postale francese. Usa questo "^ ((0 [1-9]) | ([1-8] [0-9]) | (9 [0-8]) | (2A) | (2B)) [0-9] {3} $ "-> developpez.net/forums/d518232/webmasters-developpement-web/…
Vincent D.

Sto usando i18napis.appspot.com/address/data/GB ora; ci sono problemi con questo servizio?
mgol

1
Piccola correzione al commento di @ kiko-software: l'ultima versione contenente i dati del codice postale è 27.0.3 .
Sietse,

89

usa questi regx

$ZIPREG=array(
    "US"=>"^\d{5}([\-]?\d{4})?$",
    "UK"=>"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
    "DE"=>"\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b",
    "CA"=>"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$",
    "FR"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
    "IT"=>"^(V-|I-)?[0-9]{5}$",
    "AU"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
    "NL"=>"^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$",
    "ES"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
    "DK"=>"^([D|d][K|k]( |-))?[1-9]{1}[0-9]{3}$",
    "SE"=>"^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$",
    "BE"=>"^[1-9]{1}[0-9]{3}$",
    "IN"=>"^\d{6}$"
);

7
Uno dei migliori tentativi che ho visto per rispondere effettivamente al PO. Diventa più lento man mano che pubblichi di più ma con un approccio chiaro e chiaro.
Rob,

3
Non si rallenta man mano che aggiungi di più come suggerisce Rob poiché sceglieresti una delle regex dal prefisso del paese.
Thomaschaaf,

2
Vedo che lo hai pubblicato nel 2012. Ne hai ancora da allora?
rybo111,

@ rybo111 verifica la risposta di Chi.
Giulio Caccin,

5
@ddunn801, there's a (whomping big) differencee between validating the pattern and authenticating the postal code. Authenticating the codes is whole orders of magnitude more difficult since (at least in the U.S.) postal codes are added and dropped regularly. In an ideal world, you would perform a quick-check to validate the pattern before submitting to a service (e.g., USPS) to validate the entire mailing address (services like this are paid, you'd hate to waste the value with bad data). Alas, the world is far from ideal.
JBH

48
  1. Every postal code system uses only A-Z and/or 0-9 and sometimes space/dash

  2. Non tutti i paesi usano codici postali (es. Irlanda fuori Dublino), ma lo ignoreremo qui.

  3. Il formato del codice postale più breve è la Sierra Leone con NN

  4. Il più lungo è Samoa americane con NNNNN-NNNNNN

  5. Dovresti consentire uno spazio o un trattino.

  6. Non dovrebbe iniziare o terminare con spazio o trattino

Questo dovrebbe coprire quanto sopra:

(?i)^[a-z0-9][a-z0-9\- ]{0,10}[a-z0-9]$

8
Questa sembra essere l'unica risposta che fornisce un controllo di integrità (che è probabilmente quello che voleva l'OP) piuttosto che una validazione completa di ogni possibile combinazione. Esattamente quello che volevo grazie
Lukos,

1
@GiulioCaccin H0H0H0 is a valid Canadian Postal Code (which children use to get letters from Canada Post pretending to be Santa Claus), but that doesn't mean it's a valid customer postal code :)
Neil McGuigan

2
FYI, American Samoa is small enough to only has one postcode and it's 96799
naterkane

5
In my opinion this is the only good answer. It can universally be used as pre-validation in HTML pattern attribute for instance.
Blackbam

2
I think this is a good answer for the situation where one just wants to have a sanity check and not validate precisly per country. Just to have a little cleaner data without much effort -- in cases where full safety is needed, a third party plugin/service might be needed as others pointed out.
Yo Ludke

17

Trying to cover the whole world with one regular expression is not completely possible, and certainly not feasible or recommended.

Not to toot my own horn, but I've written some pretty thorough regular expressions which you may find helpful.

  • Canadian postal codes

    Basic validation:
    ^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
    
    Extended validation:
    ^(A(0[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EGHJ-NPRSTV-Z]|7[ABCEGHJ-NPRSTV-Y]|8[ABCGJ-NPRSTV-Z]|9[ABCEGHJ-NPRSTV-Z])|X(0[ABCGX]|1[A])|Y(0[AB]|1[A]))[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
  • US ZIP codes

    ^[0-9]{5}(-[0-9]{4})?$
  • UK post codes

    ^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$

It is not possible to guarantee accuracy without actually mailing something to an address and having the person let you know when they receive it, but we can narrow things by down by eliminating cases that we know are bad.


The extended version for Canadian Postal Codes might have something wrong or missing, as it says that the following postal code is invalid: E3G 0A1, although it is a valid one.
fsschmitt

I have validated against all 845,495 postal codes in Canada and this regex string has some fixes on the Extended validation to support all of these postal codes. Here is the new regex string for the extended validation on Canadian Postal Codes: pastebin.com/vazqFKy4
fsschmitt

14

This looks like a good reference although it's not in Regex.

Really, unless you're actually shipping something to your users, I don't think it's worth the effort. And if you are shipping it, there are address cleaning tools/services you can look into to make it way easier on yourself.


Also, even if it is the correct zip code today it very well might change in the future. USPS is constantly adding new ones and splitting areas. The only way you can keep up is to validate at the time you are actually shipping something. Some towns even elect to change their own zip code for a variety of reasons.
NotMe

Looks like someone took the wiki article you posted above and output it to JSON with the postal/zip code regex for each country - gist.github.com/matthewbednarski/…
Chris Smith

8

We use the following:

Canada

([A-Z]{1}[0-9]{1}){3}   //We raise to upper first

America

[0-9]{5}                //-or-
[0-9]{5}-[0-9]{4}       //10 digit zip

Other

Accept as is


1
I'd suggest adding an optional -[0-9]{4} to the US one. Some people do use their ZIP+4.
David Thornley

4
/[0-9]{5}(?:-[0-9]{4})?/ lets you validate both styles from the US at the same time.
Chas. Owens

2
@Chas.Owens adding ^ and $ ensure they can't type anything else before or after, like "12345aaa" ... /^[0-9]{5}(?:-[0-9]{4})?$/
Tim Franklin

7

Depending on your application, you might want to implement regex matching for the countries where most of your visitors originate and no validation for the rest (accept anything).


6
.* 

Big Jump forgot about line breaks, blanks and control characters.

International postal codes are a kind of halting problem.


6

Please note that this is quite a hard problem, as stated by the accepted answer. I guess it didn't deter the folks at geonames.org though. They have a file a country info file, which doesn't fit whole into this answer - limit is at 30000 chars apparently. There are regexes for about 150 countries.

I extracted the bits relevant to this question here :

AD ^(?:AD)*(\d{3})$
AM ^(\d{6})$
AR ^([A-Z]\d{4}[A-Z]{3})$
AT ^(\d{4})$
AU ^(\d{4})$
AX ^(?:FI)*(\d{5})$
AZ ^(?:AZ)*(\d{4})$
BA ^(\d{5})$
BB ^(?:BB)*(\d{5})$
BD ^(\d{4})$
BE ^(\d{4})$
BG ^(\d{4})$
BH ^(\d{3}\d?)$
BM ^([A-Z]{2}\d{2})$
BN ^([A-Z]{2}\d{4})$
BR ^(\d{8})$
BY ^(\d{6})$
CA ^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]) ?(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$
CH ^(\d{4})$
CL ^(\d{7})$
CN ^(\d{6})$
CR ^(\d{4})$
CU ^(?:CP)*(\d{5})$
CV ^(\d{4})$
CX ^(\d{4})$
CY ^(\d{4})$
CZ ^(\d{5})$
DE ^(\d{5})$
DK ^(\d{4})$
DO ^(\d{5})$
DZ ^(\d{5})$
EC ^([a-zA-Z]\d{4}[a-zA-Z])$
EE ^(\d{5})$
EG ^(\d{5})$
ES ^(\d{5})$
ET ^(\d{4})$
FI ^(?:FI)*(\d{5})$
FM ^(\d{5})$
FO ^(?:FO)*(\d{3})$
FR ^(\d{5})$
GB ^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2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})$

Hopefully I didn't make any mistake, my regex-fu is pretty weak.


1
I would like to point out that the regex for France and Great Britain do not take into account possible spaces; In France, postal codes can be input with a space between the second and third digits (i.e. 75 001 instead of 75001). British post codes are quite often written with a space (i.e. SW1 1AA instead of SW11AA).
salcoin

@salcoin Thanks for the input, I did not notice that (even though I am French). Looks like Chi's answer is better in this regard.
nha

because str_replace a space with no space is super taxing right? :p
Robert Pounder

6

If someone is still interested in how to validate zip codes I've found a solution:

Using Google Geocoding API we can check validity of ZIP code having both Country code and a ZIP code itself.

For example I live in Ukraine so I can check like this: https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:80380|country:UA

Or using JS API: https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

Where 80380 is valid ZIP for Ukraine, actually every (#####) is valid.

Google returns ZERO_RESULTS status if nothing found. Or OK and a result if both are correct.

Hope this will be helpful.


The only issue would be the limit on the number of queries, which, depending on the site/size, could be an issue.
Darryl Hein

@DarrylHein of course but that's now quite a big price to get it working =)
Romko


2

The problem is going to be that you probably have no good means of keeping up with the changing postal code requirements of countries on the other side of the globe and which you share no common languages. Unless you have a large enough budget to track this, you are almost certainly better off giving the responsibility of validating addresses to google or yahoo.

Both companies provide address lookup facuilities through a programmable API.


1

Why are you doing this and why do you care? As Tom Ritter pointed out, it doesn't matter whether you even have a ZIP/postal code at all, much less whether it's valid or not, until and unless you are actually going to be sending something to that address. Even if you expect that you will be sending them something someday, that doesn't mean you need a postal code today.


Yeah but if they're going to be entering one, might as well make sure it's correct at that point. However, I agree with one of the other answers that basically says, make it validate for the countries that you think will be the majority of your customers.
cdmckay

1
Some credit clearing houses will not accept a bill unless the zip is correct. I would rather validate the zip on input, rather than submit the charge and have it rejected.
SamGoody

1

As noted elsewhere the variation around the world is huge. And even if something that matches the pattern does not mean it exists.

Then, of course, there are many places where postcodes are not used (e.g. much or Ireland).


Actually, probably all of Ireland, as I don't think D1, D2, etc. are considered proper post codes as you can't identify an address using just this code and a street number.
Dónal

1

There are reasons beyond shipping for having an accurate postal code. Travel agencies doing tours that cross borders (Eurozone excepted of course) need this information ahead of time to give to the authorities. Often this information is entered by an agent that may or may not be familiar with such things. ANY method that can cut down on mistakes is a Good Idea™

However, writing a regex that would cover all postal codes in the world would be insane.


1
It is only a good idea until the code starts rejecting valid zipcodes either because it is buggy or the zipcodes have changed. Validation is something that must either be right or not there at all. At the very least there should be an override option.
Chas. Owens

1

Dato che ci sono così tanti casi limite per ogni paese (ad es. Gli indirizzi di Londra possono usare un formato leggermente diverso rispetto al resto del Regno Unito) Non penso che ci sia una regex definitiva diversa da forse:

[0-9a-zA-Z]+

Meglio andare con uno schema abbastanza ampio (anche se non abbastanza ampio come quello sopra), o trattare ogni paese / regione con uno schema specifico proprio!

AGGIORNAMENTO: Tuttavia, potrebbe essere possibile costruire dinamicamente una regex in base a molte regole più piccole, specifiche per regione, ma non sono sicuro delle prestazioni!

Molti modelli specifici per paese sono disponibili sul sito RegExLib .


1

Qualcuno stava chiedendo l'elenco degli indirizzi postali di formattazione e penso che questo sia quello che stava cercando ...

Guida obbligatoria di Frank agli indirizzi postali: http://www.columbia.edu/~fdc/postal/ Non aiuta molto con problemi di livello stradale, tuttavia.

Il mio lavoro usa un paio di strumenti per aiutare con questo: - Servizi Lexis-Nexis, comprese le ricerche NCOA (otterrai la standardizzazione degli indirizzi per "gratis") - "Dati Melissa" http://www.melissadata.com


1

Questo è un RegEx molto semplice per la convalida del codice postale statunitense (non ZipCode Plus Four):

(?!([089])\1{4})\d{5}

Sembra che tutti e cinque i numeri siano codici postali validi tranne 00000, 88888e99999 .

Ho provato questo RegEx con http://regexpal.com/

SP


Questo RegEx non impone quattro cifre per la porzione zip + 4. Ad esempio, considera "92122-1" un codice postale valido.
Sensei James,

0

Se Zip Codeconsente caratteri e cifre (alfanumerici), sotto regex verrebbero utilizzati dove corrispondono, 5 o 9 o 10 caratteri alfanumerici con un solo hypen ( -):

^([0-9A-Za-z]{5}|[0-9A-Za-z]{9}|(([0-9a-zA-Z]{5}-){1}[0-9a-zA-Z]{4}))$
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.