Zipcode Or Postal Code Search – Regex

Searching to see if a string of text or a full file of text or anything else in between for a zip or postal code? This three regexes below will help you do just that.

The first regex will validate the input value for a postal code, whether if the input character was capitalized or not. This is good for cases where information must be verified correctly but not to constrain to the fact which letter have to be capital. Nevertheless, the pattern still has to be v1v1v1 or v1v 1v1 for the regex to match.

Zipcode code can be in the format of xxxxx or xxxxx-xxxx. Ultimately this regex doesn’t require you to turn on the //i option for case insensitive match. If you do however requires case sensitive match. remove all capital letters to match only lowercase. Remove all lowercase to match uppercase.

^(^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]{1} {0,1}\d{1}[A-Za-z]{1}\d{1}$)|(^\d{5}(-\d{4})?$)$

This below code is for postal code check only. It is a split from the regex above. I will split this regex string and give more detail on what part of the string does what in the below.

^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]{1} {0,1}\d{1}[A-Za-z]{1}\d{1}$

This below is the smaller chunk of the postal code check regex above.

[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1} // Check for the first letter in the postal code. Canada postal code can only contain ABCEGHJKLMNPRSTVXY for the first letter.
\d{1} // This will check for any digit and need at least one of them.
[A-Za-z]{1} // This will check for any letter from A-Z, whether capitalized or not.
 {0,1} // This would check for a single space and no space would also be fine. Notice the {0,1}. That is 0 match or 1 match but can't be 2. 
\d{1}[A-Za-z]{1}\d{1} // This will do all the mention previously

This is the regex for evaluating whether if the data does contain a Zipcode. This regex can check for both format xxxxx or xxxxx-xxxx. You can remove the (-\d{4}) to only check for xxxxx.


This post was written by Kevin and was first post @
Original Post Name: "Zipcode Or Postal Code Search – Regex".
Original Post Link:


Random Article You May Like

One thought on “Zipcode Or Postal Code Search – Regex

Leave a Reply

Your email address will not be published. Required fields are marked *