Need to match zip codes or postal codes? Of course, no two countries use the same format. But here are solutions for USA, Canada, and the United Kingdom.
The USA format is simple, five digits as 99999 or zip+4 as 99999-9999. A simple RegEx could be:d{5}(-d{4})?
If you want to omit zips with a trailing hyphen (as in 99999-) then you could use a lookahead condition:d{5}(?(?=-)-d{4})
Canada is a little trickier, the format looks like A1A 1A1 which can be easily matched with:[A-Z]d[A-Z] d[A-Z]d
However, there is one rule that may be employed to improve validation, the opening character of the set of characters (technically called the “forward sortation area” or FSA) identifies the province, territory, or region (there are 18 characters that are valid in this position, A for Newfoundland and Labrador, B for Nova Scotia, K, L, N and P for Ontario excluding Toronto which uses M, and so on.), and so validation should ideally check to ensure that the first character is a valid one. And so, here is a better Canadian postal code regular expression:[ABCEGHJKLMNPRSTVXY]d[A-Z] d[A-Z]d
Good old UK is the trickiest of the three. United Kingdom postcodes, as defined by the Royal Mail, are five, six, or seven characters and digits (that includes a single space). Postcodes are made up of two parts, the “outward postcode” (or outcode), and the “inward postcode” (or incode). The outcode is one or two alphabetical characters followed by one or two digits, or one or two characters followed by digit and a character. The incode is always a single digit followed by 2 characters (any characters excluding C, I, K, M, O, and V). The incode and outcode are separated by a space. Here’s the regular expression:[A-Z]{1,2}d[A-Zd]? d[ABD-HJLNP-UW-Z]{2}
If you have any other countries or formats to share, please do so.
Leave a Reply