New blogMaking an AI Agent You Can Trust With Money

★ Identity & contact · regex

Regex for US ZIP Code

Matches 5-digit US ZIP codes and the ZIP+4 format (12345-6789). Leading zeros are kept, as in New England ZIPs.

  • Runs in your browser
  • No signup

Try the us zip code pattern

Read it in plain English (best-effort)

  • ^start of a line
  • [0-9]one character from: 0–9
  • {5}exactly 5 of the previous
  • (?:start a group (not captured)
  • -the character '-'
  • [0-9]one character from: 0–9
  • {4}exactly 4 of the previous
  • )end of group
  • ?the previous is optional
  • $end of a line

One sample per line works well with the m flag on anchored patterns.

Waiting for a pattern
01

The pattern, piece by piece

/^[0-9]{5}(?:-[0-9]{4})?$/
Pattern explanation
PartWhat it does
^[0-9]{5}exactly five digits
(?:-[0-9]{4})?optional hyphen and four more digits (ZIP+4)
$end of the string
02

What it accepts and rejects

Every sample below is checked automatically in JavaScript and Python. The tester above is preloaded with all of them, one per line.

Should match
Should match
94105✓
10001✓
02134✓
94105-1234✓
00501✓
99950✓
Should not match
Should not match
9410✗
941051✗
94105-123✗
94105 1234✗
ABCDE✗
94105-✗
03

Copy it into your code

RE2-safeNo lookarounds or backreferences, so the same pattern works in Go's RE2 engine and in Rust's regex crate.

const usZipRe = /^[0-9]{5}(?:-[0-9]{4})?$/;

export function isValidUsZip(value) {
  return usZipRe.test(value.trim());
}
04

When not to use regex for this

Store ZIPs as strings, never numbers, or 02134 becomes 2134. To check a ZIP is real or matches a city, use a postal data API.

05

Questions engineers actually ask

Why store ZIP codes as text?
Leading zeros matter. Numeric columns silently drop them.
Does it accept spaces in ZIP+4?
No. The USPS format uses a hyphen; normalise spaces to a hyphen before validating if users type them.
What is catastrophic backtracking?
Some patterns, usually nested quantifiers like (a+)+, make a backtracking engine try an exponential number of paths on input that almost matches. The tester stops any run after 300ms, so a bad pattern can't freeze your tab. In production, that same pattern can take down a server (a ReDoS attack).
06

More identity & contact patterns

07

More from the workbench

Fine print

Tools: on the house.
Engineer: by the hour.

The regex was free. Code that doesn't need one is the upgrade: typed schemas, validated once at the edge, trusted everywhere after.

I'm Himanshu, an AI and full-stack engineer. I build MVPs, AI agents and the growth plumbing around them for early-stage startups.