^\d{5}(-\d{4})?$ This pattern validates US ZIP codes: exactly five digits, optionally followed by a hyphen and four more digits for the ZIP+4 extended form. It matches both 12345 and 12345-6789. Validation patterns answer a yes/no question about an entire input: does this string conform to the expected format? They are anchored with ^ and $ so the whole value must match, and they belong at the edge of your system — form fields, API payloads and import files — where rejecting bad input early prevents downstream errors. A validation regex is a contract check, not a transformation. It needs no special flags. Apply it to the whole input as a format contract. It checks format only, not whether the ZIP actually exists or maps to a real area — use a postal database for that. Leading zeros are significant (e.g. 00501) and preserved because the pattern uses digits, not a numeric parse. Other countries have alphanumeric postal codes (e.g. UK, Canada) that need entirely different patterns. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.
Token-by-token explanation
^ — start anchor\d{5} — exactly five digits (the base ZIP)(-\d{4})? — optional hyphen plus four digits (ZIP+4)$ — end anchor
What it matches
123450050112345-678990210 What it does not match
123412345612345-678ABCDE12345 6789 When to use it
Reach for a validation pattern when data crosses a trust boundary: a signup form, an API request body, a CSV import or a configuration value. Run it before any processing so malformed input is rejected with a clear message instead of causing a cryptic failure later. Keep the pattern in one shared place, document the exact format it accepts, and pair it with a real parser when the value has semantics (dates, numbers, addresses) that a shape check alone cannot confirm.
Caveats
- It checks format only, not whether the ZIP actually exists or maps to a real area — use a postal database for that.
- Leading zeros are significant (e.g. 00501) and preserved because the pattern uses digits, not a numeric parse.
- Other countries have alphanumeric postal codes (e.g. UK, Canada) that need entirely different patterns.
Code examples
const re = /^\d{5}(-\d{4})?$/;
const input = "12345";
if (re.test(input)) {
// valid: proceed
} else {
// reject with a helpful message
} import re
rx = re.compile(r"^\d{5}(-\d{4})?$")
value = "12345"
if rx.fullmatch(value):
pass # valid
else:
raise ValueError("invalid format") import java.util.regex.*;
Pattern p = Pattern.compile("^\\d{5}(-\\d{4})?$");
Matcher m = p.matcher("12345");
boolean ok = m.matches(); // whole input must conform <?php
$subject = "12345";
if (preg_match('/^\d{5}(-\d{4})?$/', $subject, $m)) {
// $m[0] is the full match
} How to test it
Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.
Frequently asked questions
What is ZIP+4?
The four-digit extension identifies a more specific delivery segment within the five-digit ZIP area, written as 12345-6789. The optional group accepts both forms.
Does it validate that the ZIP is real?
No — it only checks the digit format. Confirming a ZIP exists and matches a city/state requires a postal reference database or address-validation service.
Should validation regexes be anchored?
Yes — use ^ and $ (or fullmatch) so the entire input must conform. Without anchors, a valid-looking substring inside garbage would pass, letting malformed data through your validation layer.
What is catastrophic backtracking and how do I avoid it?
Nested quantifiers like (a+)+ can explode exponentially on non-matching input, freezing the engine (ReDoS). Avoid ambiguous nesting, prefer atomic groups or possessive quantifiers where supported, and bound input length.
Try the Regex Tester
Live regex matching with groups, flags and explanations.