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:
If you want to omit zips with a trailing hyphen (as in 99999-) then you could use a lookahead condition:
Canada is a little trickier, the format looks like A1A 1A1 which can be easily matched with:
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:
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:
If you have any other countries or formats to share, please do so.