One regex for checking US and Canada zip codes

I am developing a program for office supplies. Customers can choose their region both in the USA and in Canada. When they enter the address, they must enter the ZIP / Postal code. I am trying to check a field, but I cannot use reg exp for the USA or Canada. I need a regular expression that is checked for both the zip code of the country.

+8
regex
source share
2 answers

Not knowing which language you are using, I will not use abbreviations for character classes:

^[0-9]{5}$|^[AZ][0-9][AZ] ?[0-9][AZ][0-9]$ 

Depending on your language, you can shorten this to

 ^([0-9]{5}|[AZ][0-9][AZ] ?[0-9][AZ][0-9])$ 

or

 ^(\d{5}|[AZ]\d[AZ] ?\d[AZ]\d)$ 

To support ZIP + 4:

 ^(\d{5}(-\d{4})?|[AZ]\d[AZ] ?\d[AZ]\d)$ 

And if you want to really understand your Canada codes:

 ^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$ 
+16
source share

In response to the above, you can add (? I) to the beginning of the regular expression to make case insensitive. So it will look like this:

 ^(?i)(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$ 
+1
source share

All Articles