Regex: US ZIP code
A US ZIP code is five digits, optionally followed by a dash and four more (ZIP+4), as in 10001-1234. The pattern accepts exactly those two forms.
Pattern
^\d{5}(?:-\d{4})?$ How it works
- ^
- Start of the string.
- \d{5}
- Five digits.
- (?:-\d{4})?
- Optionally, a dash and four more digits.
- $
- End of the string.
Matches
- 90210
- 10001-1234
- 00501
Doesn't match
- 9021
- 902101
- 90210-12
- ABCDE
In your language
- JavaScript
/^\d{5}(?:-\d{4})?$/A literal;
new RegExp(source, flags)builds the same from a string.- Python
re.compile(r"^\d{5}(?:-\d{4})?$", re.ASCII)A raw string, so backslashes reach
reas written.re.ASCIIkeeps\dto0-9, as in JavaScript (Python matches any Unicode digit otherwise). Usere.fullmatchto test a whole string.- Java
Pattern.compile("^\\d{5}(?:-\\d{4})?$")A normal string literal, so every backslash is doubled.
matcher(s).matches()tests the whole string.- Go
regexp.MustCompile(`^\d{5}(?:-\d{4})?$`)A raw string in backticks. RE2 runs in linear time but has no lookaround and no backreferences.
- PHP
preg_match('/^\d{5}(?:-\d{4})?$/D', $input)PCRE with
/delimiters inside a single-quoted string. Without theDmodifier,$also matches before a final newline, so it is added to patterns that end in$.- C#
new Regex(@"^\d{5}(?:-\d{4})?$", RegexOptions.ECMAScript)A verbatim string: backslashes stay, a quote is doubled.
RegexOptions.ECMAScriptkeeps\dto0-9, as in JavaScript.$also matches before a final newline; to reject one, end the pattern with\zinstead.
Common mistakes
Store ZIP codes as text
ZIP codes in New England start with 0 (
02108is in Boston). Stored as a number, the leading zero is lost and2108no longer matches.Shape is not existence
Fewer than half of the possible five-digit codes are in use. Only a lookup against USPS data tells you a code is real.
Other countries, other shapes
Canada writes
A1A 1A1(^[A-Z]\d[A-Z] ?\d[A-Z]\d$), Poland00-950(^\d{2}-\d{3}$), and the UK has several shapes such asSW1A 1AA. Choose the pattern from the address's country.