tools / regex library / uk postcode
regex pattern · ready to copy

Regex for matching UK postcodes

Match standard UK postcode formats (W1A 1AA, SW1W 0NY, GIR 0AA).

intermediate javascript / pcre / python4 use cases

The pattern

\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b

Test cases

InputResult
SW1A 1AAmatches
EC1A 1BBmatches
W1A 0AXmatches
GIR 0AAmatches
12345 (US)rejects
EC1A1BB (no space — depends on policy)rejects
ZZ99 9ZZ might or might not be valid (test postcodes)rejects

Edge cases & caveats

Royal Mail's official spec is much stricter — handles 12 sub-formats. This regex is permissive enough for most form validation but allows invalid postcodes. For e-commerce, use Royal Mail PAF API.

Common use cases

Try variations against your data
regexlab is a free in-browser tester with side-by-side match highlighting, group inspector, and named-capture export to JS/Python/PCRE.
Open regexlab  

Related

username · ethereum address · email address · hex color · ↗ generate test addresses