breakitdown

Regex for a US ZIP code

Answer

^\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.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. ^Start of the stringanchor
  2. \dA digit (0-9)character type
  3. {5}Repeat it exactly 5 timesquantifier
  4. (?:…)Non-capturing group: groups without rememberinggroup
  5. -The character '-' literallyliteral
  6. \dA digit (0-9)character type
  7. {4}Repeat it exactly 4 timesquantifier
  8. ?Then repeat the whole group optionally (zero or one time)quantifier
  9. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
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

Gotchas

Related explainers

← Explain any regular expression