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
| Input | Result |
|---|---|
| SW1A 1AA | ✓matches |
| EC1A 1BB | ✓matches |
| W1A 0AX | ✓matches |
| GIR 0AA | ✓matches |
| 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
- UK shipping form validation
- address normalization
- geo-lookup pipeline
- delivery zone routing
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