Exploring the Web: An Apple a day

Main menu

Canada Postal Code & US Zip Code Regex

Bookmark/Search this post

I decided to write a simple Canadian Postal Code and US Zip Code Regex. There are already good ones on the web, like here for example. But, I decided to write my own to make it slightly more accurate.

Canadian Postal Code Regex

Canada's Postal Code format is 'A1A 1X1' or 'a1a1x1'. Its made up of two parts. Forward Sortation Area (FSA) and Local Delivery Unit (LDU). Read more on wikipedia. The letters D, F, I, O, Q, or U are not used on postal Code. So, the Postal Code would be roughly (note that when applying the regex, the case-insensitive (i) modifier should be used):

US Zip Code Regex

US Zip Code format seems to be straightforward. It needs to have 5 digits followed by an optional 4 digit. So, the Zip Code would be roughly:

Merging US & Canadian Postal Code

Now, both Postal Code and Zip Code could be merged, using an OR (|) operator, into one regex:

Hello, if you apply the case-insensitive modifier (i), then the regex would become case insensitive. If you read my blog I mentioned the following thing: "note that when applying the regex, the case-insensitive (i) modifier should be used".

Most regex library supports case insensitive modifier. If you are using a language where it doesn't support the case-insensitive modifier, then you can manually add another (OR |) and repeat the whole regex with its lower-case.