Regex for US ZIP code

Use /^\d{5}(?:-\d{4})?$/ to check that a whole string is a valid for US ZIP code. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^\d{5}(?:-\d{4})?$/
Open in Regex Tester
InputResult
90210✓ Match
10001-1234✓ Match
02134✓ Match
9021✗ No match
902101✗ No match
90210-12✗ No match
90210 1234✗ No match

How the pattern works

PartMeaning
^\d{5}Five digits
(?:-\d{4})?Optional ZIP+4 extension: a dash and four digits
$End of the string

Code examples

JavaScript

const re = /^\d{5}(?:-\d{4})?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'\d{5}(?:-\d{4})?', value))

PHP

preg_match('/^\d{5}(?:-\d{4})?$/', $value) === 1;

Notes and limitations

Keep ZIP codes as strings, not numbers — codes in New England start with 0 and would lose it.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for US ZIP code?
/^\d{5}(?:-\d{4})?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 90210, 10001-1234, 02134. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.