How the pattern works
| Part | Meaning |
|---|---|
[A-Z]{1,2} | Postcode area: one or two letters |
\d[A-Z\d]? | District: a digit, optionally followed by a letter or digit |
? | Optional space |
\d[A-Z]{2} | Inward code: a digit and two letters |
i flag | Case-insensitive |
Code examples
JavaScript
const re = /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}', value, re.I))PHP
preg_match('/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i', $value) === 1;
Notes and limitations
This checks the shape of a postcode, not whether it exists. Normalize to upper case with a single space before the last three characters when you store 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 UK postcode?
/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: SW1A 1AA, M1 1AE, B33 8TH, cr2 6xh. 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.