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.
| Input | Result | Matched |
|---|---|---|
| 01001 | matches | 01001 |
| 90210 | matches | 90210 |
| 90210-1234 | matches | 90210-1234 |
| 9021 | no match | — |
| 90210-12 | no match | — |
| 90210 1234 | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID