Regex for UK postcodes
A regular expression for UK postcodes built from the six formats Royal Mail publishes and the pattern in the UK government's data standard, with what it checks and what only a lookup can tell you.
This tool runs in your browser. We never send what you type or paste to a server.
The pattern
/^(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})$/Royal Mail's addressing guidance, as published by the Universal Postal Union, lists six formats, where A is a letter and 9 a digit: A9 9AA, A99 9AA, AA9 9AA, AA99 9AA, A9A 9AA and AA9A 9AA, with GIR 0AA as the only exception. This pattern accepts exactly those shapes, with the space optional.
The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.
How it works, token by token
| Part | Meaning |
|---|---|
^(?: | Start of the string, and a group around the two alternatives so the anchors apply to both. |
GIR␣?0AA | The one exception to the rules: GIR 0AA, historically Girobank's postcode. |
| | Or a normal postcode: |
(?: | The outward code (area and district), in one of four shapes: |
[A-Z][0-9]{1,2} | A9 or A99, such as M2 and M34. |
| | or |
[A-Z][A-HJ-Y][0-9]{1,2} | AA9 or AA99, such as CR0 and DN16. The second letter is never I or Z, as in the government pattern. |
| | or |
[A-Z][0-9][A-Z] | A9A, such as W1A. |
| | or |
[A-Z][A-HJ-Y][0-9][A-Z] | AA9A, such as EC1A. |
) | End of the outward code. |
␣? | An optional space. Royal Mail writes one, but people often leave it out. |
[0-9][A-Z]{2} | The inward code (sector and unit): a digit and two letters, such as 1AA. |
)$ | End of the group and of the string. |
␣ stands for a space character.
The pattern only accepts capital letters. Uppercase the input before checking, as in the normalising code further down, rather than adding the i flag: case-insensitive matching of letter ranges can behave differently between engines and locales.
What it matches and what it rejects
| Input | Result | Why |
|---|---|---|
M2 5BQ | matches | A9 9AA |
M34 4AB | matches | A99 9AA |
CR0 2YR | matches | AA9 9AA |
DN16 9AA | matches | AA99 9AA |
W1A 4ZZ | matches | A9A 9AA |
EC1A 1HQ | matches | AA9A 9AA |
SW1A1AA | matches | The space is optional. |
GIR 0AA | matches | The special case. |
JE2 4UH | matches | Jersey: Crown dependency postcodes use the same formats. |
sw1a 1aa | rejected | Lowercase: uppercase the input first. |
SW1A 1AA | rejected | Two spaces: collapse whitespace first. |
SW1A-1AA | rejected | A hyphen is not a separator. |
SW1A 1A | rejected | The inward code needs two letters. |
AI1 1AA | rejected | I is never the second letter. |
1AB 2CD | rejected | A postcode starts with a letter. |
ABC 1DE | rejected | Three letters in a row is not one of the six formats. |
BFPO 801 | rejected | British Forces Post Office numbers are a separate format. |
The government's pattern
The UK government's bulk data transfer XML schema defines a UKPostCodeType "corresponding to BS7666" with the pattern below. XML Schema patterns always match the whole value, so it is shown here with ^(?: and )$ added; the rest is copied unchanged and tested like everything else on this page:
/^(?:([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$/| Input | Result | Why |
|---|---|---|
SW1A 1AA | matches | Fine. |
sw1a 1aa | matches | It accepts lowercase. |
ABC 1DE | matches | Accepted: the digit in the last outward shape is optional, so three letters slip through. |
SW1A1AA | rejected | The space is required. |
AI1 1AA | rejected | I as the second letter. |
It is a reasonable reference, but two details surprised us when we tested it: the space is required, and [0-9]? in its last outward shape lets three letters through. The pattern at the top of this page keeps the official structure and letter rule, makes the space optional and requires that digit.
Normalising before you check
Accept what people type, then tidy it: uppercase it, remove all whitespace, check it, and put one space back before the last three characters. The inward code is always a digit and two letters, so the split point never moves.
const POSTCODE = /^(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})$/;
function normalisePostcode(input) {
const s = input.toUpperCase().replace(/\s+/g, '');
if (!POSTCODE.test(s)) return null;
return `${s.slice(0, -3)} ${s.slice(-3)}`; // the inward code is always the last three characters
}
console.log(normalisePostcode(' sw1a1aa ')); // → SW1A 1AA
console.log(normalisePostcode('ec1a 1hq')); // → EC1A 1HQ
console.log(normalisePostcode('SW1A 1A')); // → nullimport re
POSTCODE = re.compile(r'(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})')
def normalise_postcode(text):
s = re.sub(r'\s+', '', text.upper())
if not POSTCODE.fullmatch(s):
return None
return f'{s[:-3]} {s[-3:]}'
print(normalise_postcode(' sw1a1aa ')) # → SW1A 1AA
print(normalise_postcode('ec1a 1hq')) # → EC1A 1HQ
print(normalise_postcode('SW1A 1A')) # → None
What the format cannot tell you
A postcode that fits the format may not exist: the pattern cannot know which combinations have been issued. Postcodes are also created and retired over time. To know whether one is real, look it up in Royal Mail's Postcode Address File (PAF), which is licensed, or the ONS Postcode Directory, which the Office for National Statistics publishes free. For a delivery address, an address lookup service built on PAF also fills in the street, which saves typing.
British Forces Post Office addresses use BFPO followed by a number, which this pattern rejects; accept them separately if your users need them. Crown dependency postcodes such as Jersey (JE), Guernsey (GY) and the Isle of Man (IM) follow the same formats and pass.
In JavaScript, Python, PHP and C#
JavaScript
const re = /^(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})$/;
console.log(re.test('M2 5BQ')); // → true
console.log(re.test('sw1a 1aa')); // → false
Python
import re
pattern = re.compile(r'(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})')
print(bool(pattern.fullmatch('M2 5BQ'))) # → True
print(bool(pattern.fullmatch('sw1a 1aa'))) # → False
PHP
<?php
$pattern = '/^(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})$/D';
echo preg_match($pattern, 'M2 5BQ'), "\n"; // → 1
echo preg_match($pattern, 'sw1a 1aa'), "\n"; // → 0
C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^(?:GIR ?0AA|(?:[A-Z][0-9]{1,2}|[A-Z][A-HJ-Y][0-9]{1,2}|[A-Z][0-9][A-Z]|[A-Z][A-HJ-Y][0-9][A-Z]) ?[0-9][A-Z]{2})\z");
Console.WriteLine(pattern.IsMatch("M2 5BQ")); // → True
Console.WriteLine(pattern.IsMatch("sw1a 1aa")); // → FalseEach version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.
The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.
Questions
Is the space in a UK postcode required?
Royal Mail writes postcodes with one space between the outward and inward code, but people often leave it out. The pattern on this page accepts both, and the normalising code puts the space back before the last three characters.
How long is a UK postcode?
Between five and seven characters without the space: the outward code has two to four characters and the inward code always has three.
Does the pattern check that a postcode exists?
No. It checks the shape. Use the ONS Postcode Directory (free) or Royal Mail's Postcode Address File (licensed) to check that a postcode is real.