RegexBuilder · regex answers
Regex for a UK postcode
/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/iThe 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.
| Input | Result | Matched |
|---|---|---|
| SW1A 1AA | matches | SW1A 1AA |
| EC1A1BB | matches | EC1A1BB |
| M1 1AE | matches | M1 1AE |
| CR2 6XH | matches | CR2 6XH |
| SW1A 1A | no match | — |
| 1AA SW1 | no match | — |
| SW1A 1AA | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID