Regex to Match a UK Postcode
Copy the pattern, paste UK addresses, and watch each postcode light up. Below: how the outward and inward codes are structured.
What this pattern matches
It matches a UK postcode: an outward code (area + district) followed by an optional space and an inward code (sector + unit).
Part by part
[A-Z]{1,2} — one or two letters for the postcode area.
\d[A-Z\d]? — the district: a digit, then an optional digit or letter (e.g. 1A in EC1A).
? — an optional space.
\d[A-Z]{2} — the inward code: a digit and two letters.
Case and validation
Add the case-insensitive flag for lower-case input, and anchor with ^…$ to validate a single postcode field.
Use it in your code
import re
text = "SW1A 1AA, EC1A 1BB, M1 1AE, B33 8TH, CR2 6XH, DN55 1PT"
pattern = r'''[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}'''
for m in re.finditer(pattern, text):
print(m.group())
const text = "SW1A 1AA, EC1A 1BB, M1 1AE, B33 8TH, CR2 6XH, DN55 1PT";
const re = new RegExp(String.raw`[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}`, "g");
console.log(text.match(re));
FAQ
Does it match all valid postcodes?
It matches the standard format used by the vast majority of postcodes. The official rules exclude a few letter combinations; add exclusions only if you need strict Royal Mail validation.
How do I make the space optional?
The pattern already uses ? for zero-or-one space, so both 'M11AE' and 'M1 1AE' match.
Should I uppercase input first?
Either normalise to uppercase before matching, or add the case-insensitive (i) flag.