Regex for a US ZIP code
^\d{5}(?:-\d{4})?$ matches a 5-digit ZIP code such as 90210, optionally followed by a hyphen and the 4-digit ZIP+4 add-on, as in 90210-1234.
JavaScript ✓PCRE ✓
No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)
^Start of the stringanchor\dA digit (0-9)character type{5}Repeat it exactly 5 timesquantifier(?:…)Non-capturing group: groups without rememberinggroup-The character '-' literallyliteral\dA digit (0-9)character type{4}Repeat it exactly 4 timesquantifier?Then repeat the whole group optionally (zero or one time)quantifier$End of the stringanchor
Examples
Checked at build time in JavaScript and in Python's re.
| Input | Matches? |
|---|---|
90210 | ✓ match |
02134 | ✓ match |
90210-1234 | ✓ match |
00501 | ✓ match |
9021 | ✗ no match |
902101 | ✗ no match |
902101234 | ✗ no match |
90210- | ✗ no match |
90210 1234 | ✗ no match |
K1A 0B1 | ✗ no match |
Try your own text
One string per line: each line is tested on its own (the m flag is added here).
How it works
ZIP codes are exactly five digits. The optional group adds the ZIP+4 extension, which the USPS writes with a hyphen. The group makes the hyphen and four digits optional together, so 90210- alone fails.
A match only means the format is right. There are about 42,000 ZIP codes in use, and 00000 matches the pattern but is not one of them. If you need to know the code exists, check it against USPS data or an address-validation API.
Variants
/^\d{5}(?:-?\d{4})?$/Also accepts ZIP+4 written without a hyphen./^[A-Z]\d[A-Z] ?\d[A-Z]\d$/iCanadian postal code format, such asK1A 0B1.
Gotchas
- Store ZIP codes as strings. New England codes start with 0 (
02134is in Boston), and a numeric column or a spreadsheet turns them into2134. - ZIP+4 without the hyphen (
902101234) fails. Some data exports omit it. The variant below accepts both. - Canadian postal codes (
K1A 0B1) and UK postcodes use letters. A US-only pattern rejects international customers.
Related explainers
- Regex for a US phone numberA regex for US and NANP phone numbers in the usual formats, with area code rules, the +1 prefix, and the...
- Regex for digits only, integers and decimalsRegexes for digits only, signed integers and decimal numbers, with the edge cases: leading zeros, a bare...
- Regex for an IPv4 addressA strict IPv4 regex that only accepts octets 0-255 and rejects leading zeros, with the edge cases where...