Possible Duplicate:
What is the ultimate postal code and zip regex?
I need Regex which can satisfy all my thr
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;
const str = `12345
12345-6789
12345 1234
123451234
12345 1234
12345 1234
1234512341
123451`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
^\d{5}(?:[-\s]\d{4})?$
^
= Start of the string.\d{5}
= Match 5 digits (for condition 1, 2, 3)(?:…)
= Grouping[-\s]
= Match a space (for condition 3) or a hyphen (for condition 2)\d{4}
= Match 4 digits (for condition 2, 3)…?
= The pattern before it is optional (for condition 1)$
= End of the string.I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.
In a previous answer from @kennytm:
^\d{5}(?:[-\s]\d{4})?$
…? = The pattern before it is optional (for condition 1)
If you want to allow both standard 5 digit and +4 zip codes, this is a great example.
To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ?
so it will always match the last 5 character group.
A useful tool I recommend for tinkering with RegEx is linked below:
https://regexr.com/
I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.
If I got anything wrong or missed an important piece of information, please correct me.