RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a UK postcode

/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i

The outward code is one or two letters, a digit, and sometimes a further letter or digit; the inward code is always a digit and two letters. The space is conventional but often missing in typed input, so it is optional here.

What each part does

[A-Z]{1,2}the area letters
\d[A-Z\d]?the district, which may carry a trailing letter or digit
?the optional space
\d[A-Z]{2}the sector digit and the two unit letters

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
SW1A 1AAmatchesSW1A 1AA
EC1A1BBmatchesEC1A1BB
M1 1AEmatchesM1 1AE
CR2 6XHmatchesCR2 6XH
SW1A 1Ano match
1AA SW1no match
SW1A 1AAno match

The mistake to avoid

Assuming the letters can be anything. The real scheme excludes several letters in each position; if you need exactness, validate against Royal Mail's Postcode Address File (PAF) rather than a pattern — Royal Mail owns and licenses it; Post Office Ltd has been a separate company since 2012 and cannot supply it.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers