The pattern
Apply it to the postcode in upper case with all spaces removed:
^(GIR0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRVWXY])[0-9][ABD-HJLNP-UW-Z]{2})$How it works
- First letter: any letter except Q, V and X.
- Second letter (when there is one): any letter except I, J and Z.
- District: one or two digits, or a digit then a letter (W1A, EC1A).
- Inward code: a digit, then two letters that are never C, I, K, M, O or V.
- GIR 0AA: the one historic exception, kept so old data still passes.
In JavaScript
const UK_POSTCODE = /^(GIR0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRVWXY])[0-9][ABD-HJLNP-UW-Z]{2})$/;
function normalise(input) {
const k = input.toUpperCase().replace(/[^A-Z0-9]/g, "");
return UK_POSTCODE.test(k) ? `${k.slice(0, -3)} ${k.slice(-3)}` : null;
}
normalise("sw1a1aa"); // "SW1A 1AA"In Python
import re
UK_POSTCODE = re.compile(r"^(GIR0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRVWXY])[0-9][ABD-HJLNP-UW-Z]{2})$")
def normalise(s: str) -> str | None:
k = re.sub(r"[^A-Z0-9]", "", s.upper())
return f"{k[:-3]} {k[-3:]}" if UK_POSTCODE.match(k) else NoneIn PHP
function normalise(string $s): ?string {
$k = preg_replace('/[^A-Z0-9]/', '', strtoupper($s));
return preg_match('/^(GIR0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRVWXY])[0-9][ABD-HJLNP-UW-Z]{2})$/', $k)
? substr($k, 0, -3) . ' ' . substr($k, -3) : null;
}Why a regex isn't enough
ZZ9 9ZZ fails the pattern, but SW1A 9ZZ passes it and doesn't exist. Terminated postcodes pass too. To know a postcode is real and still in use, look it up.
Our validate endpoint answers three things at once: valid format, known in the current edition, and live or terminated (with the nearest live postcode). It works without a key for testing and is free up to 10,000 postcode lookups a month with one.
curl "https://api.clearpostcode.co.uk/v1/postcodes/sw1a1aa/validate"
{"data": {"postcode": "SW1A 1AA", "format_valid": true, "known": true, "status": "live", "valid": true, ...}}Questions
Should I block a form when the regex fails?
Show a gentle message and let the customer correct it. Never block on a lookup alone: new-build postcodes can take up to three months to reach the open data.
Does the regex cover Northern Ireland?
Yes. BT postcodes follow the same format rules.