Regex Brazilian postal code (CEP)
A Brazilian CEP is 8 digits, written '00000-000' with a hyphen after the fifth. But nobody always types the hyphen, and real attempts split into two camps that each get it wrong in one direction: the widely used GeoNames file requires it and rejects '01001000'; a Google libaddressinput rule tolerates it but never anchors the pattern, so 'CEP 01001-000' or 'abc01001000xyz' pass. A Crystal library even has to split this into two regexes, one with the hyphen and one without. Here's an anchored pattern accepting both spellings, compared against those three real attempts.
/^[0-9]{5}-?[0-9]{3}$/passes 22/22 cases
Comparison of existing patterns
Implementation
const re = new RegExp("^[0-9]{5}-?[0-9]{3}$", "");
re.test(input);Limits
- Valide seulement la FORME (8 chiffres, tiret facultatif après le cinquième) : ne vérifie pas qu'un CEP est réellement attribué par les Correios. « 00000-000 » passe, alors qu'il n'est très probablement attribué à aucune adresse.
- Le tiret facultatif est une convention des bibliothèques, pas une règle de la page officielle des Correios, qui décrit seulement le format « 00000-000 » : si votre système exige le tiret, supprimez le « ? » du motif.
- Les trois derniers chiffres ont une signification (000-899 localités ou rues, 900-959 codes spéciaux, 970-989 et 999 unités des Correios, selon la page officielle) que ce motif n'encode pas : il ne distingue pas un CEP de rue d'un CEP d'agence.
- Un CEP de deux régions différentes ne se distingue pas par la forme seule : seul un service d'annuaire comme ViaCEP, ou le fichier des Correios, associe un code à une adresse réelle.
Postal codes for other countries
- Argentine postal code (CPA)
- Australian postcode
- Canadian postal code
- Czech postal code (PSČ)
- Dutch postal code
- French postal code
- German postal code (PLZ)
- Indian PIN code
- Irish Eircode
- Japanese postal code
- Polish postal code
- Portuguese postal code
- Spanish postal code
- Swedish postal code
- Swiss postal code (PLZ/NPA)
- UK postcode
- US ZIP code (ZIP and ZIP+4)
- All postal codes by country