RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a US ZIP code

/^\d{5}(-\d{4})?$/

Five digits, optionally followed by a hyphen and the four-digit ZIP+4 extension. Leading zeros are real: 01001 is Agawam, Massachusetts, so store ZIP codes as text and never as an integer.

What each part does

\d{5}the five-digit code
(-\d{4})?the optional ZIP+4 part

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
01001matches01001
90210matches90210
90210-1234matches90210-1234
9021no match
90210-12no match
90210 1234no match

The mistake to avoid

Storing the value as a number somewhere upstream. 01001 becomes 1001 and the regex then rejects your own data.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers