Regex for ZIP/Postal Code — Pattern Explained with Examples
This regex validates US ZIP codes in both the standard 5-digit format and the extended ZIP+4 format (5 digits, hyphen, 4 digits). It is widely used in address validation, e-commerce checkout forms, and shipping logistics systems that operate within the United States.
The Pattern
/^\d{5}(-\d{4})?$/Pattern Breakdown
| Part | Meaning |
|---|---|
^ | Start of string |
\d{5} | Exactly 5 digits (base ZIP code) |
(-\d{4})? | Optional hyphen followed by exactly 4 digits (ZIP+4 extension) |
$ | End of string |
Matches
9021012345-678910001205000213499501
Does NOT Match
1234— only 4 digits123456— 6 digits without hyphen (too long for 5-digit, not valid ZIP+4)12345-678— ZIP+4 has only 3 digits after hyphen12345-67890— ZIP+4 has 5 digits after hyphenABCD1— contains letters12345 6789— space instead of hyphen12345-— hyphen with no extension
Language Examples
JavaScript
const zipRegex = /^\d{5}(-\d{4})?$/;
console.log(zipRegex.test('90210')); // true
console.log(zipRegex.test('12345-6789')); // true
console.log(zipRegex.test('1234')); // false
console.log(zipRegex.test('12345-678')); // false
// Extract base ZIP and optional +4
const match = '12345-6789'.match(/^(\d{5})(-(\d{4}))?$/);
if (match) {
console.log(`Base: ${match[1]}, +4: ${match[3] || 'N/A'}`);
}Python
import re
zip_regex = r'^\d{5}(-\d{4})?$'
print(bool(re.match(zip_regex, '90210'))) # True
print(bool(re.match(zip_regex, '12345-6789'))) # True
print(bool(re.match(zip_regex, '1234'))) # False
print(bool(re.match(zip_regex, '12345-678'))) # False
# Extract parts
match = re.match(r'^(\d{5})(-(\d{4}))?$', '12345-6789')
if match:
print(f'Base: {match.group(1)}, +4: {match.group(3) or "N/A"}')Common Pitfalls
ZIP+4 hyphen is required — If you omit the
?quantifier on(-\d{4})?, the regex will reject 5-digit ZIP codes. The hyphen and extension should be optional together.5-digit only is common but limited — Many forms accept only 5-digit ZIP codes. If you exclude ZIP+4, use
/^\d{5}$/instead. For maximum compatibility, always accept both.Leading zeros are valid — ZIP codes like
02134(Boston) start with zero. The regex handles this correctly since\d{5}matches any five digits. Preserve leading zeros when storing.International postal codes vary widely — This pattern is US-specific. Canadian postal codes use
A1A 1A1format, UK uses alphanumeric outward/inward codes. Do not use this pattern for international addresses.
Real-World Use Cases
- E-commerce checkout — Validating shipping address ZIP codes before calculating tax and shipping rates
- CRM address standardization — Cleaning and formatting customer address data for postal mailings
- Geocoding lookups — Extracting ZIP codes from user input to perform location-based searches
FAQ
Related Patterns
- Regex for Social Security Number
- Regex for Username/Slug
- Regex for Password Strength
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro