Regex for UK postcode

Use /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i to check that a whole string is a valid for UK postcode. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i
Open in Regex Tester
InputResult
SW1A 1AA✓ Match
M1 1AE✓ Match
B33 8TH✓ Match
cr2 6xh✓ Match
12345✗ No match
SW1A1A✗ No match
SW1A 1A1✗ No match

How the pattern works

PartMeaning
[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 flagCase-insensitive

Code examples

JavaScript

const re = /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i;
re.test(value); // true or false

Python

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.