Enter a UK postcode to get deeplinks into databases and applications which return data or services based on your chosen postcode.
Try an example: SW1A 1AA
Or use the postcode drilldown below.
How do we identify a UK postcode? Read on for everything you need to know about programming with postcodes.
Each postcode consists of between two and four characters, followed by a space, followed by another three characters.
The first set of characters are the outcode (sometimes known as the outward code) whilst the second set are the incode (sometimes known as the inward code).
The outcode is itself composed of two sections, and the incode is itself also composed of two sections, which breakdown as follows:
[space]
character is used to separate the outcode from the incode.Each part of the postcode defines a geographical area.
The map below shows the areas defined by the postcode area, postcode district, postcode sector and unit postcode for example postcode WC2B 4AB:
The approach for parsing a postcode varies in complexity depending on two things:
If you just need outcode and incode, and you are expecting a postcode in the standard format - i.e. outcode and incode separated by a single space character - you can simply split on [space]
.
Example PHP code below:
array($outcode, $incode) = explode(' ', $postcode);
If you are familiar with other languages, and would like to contribute a method in another language, we would love to hear from you on Twitter or by email.
If you need postcode area, postcode district, postcode sector and unit postcode you can use a regular expression.
In the example below, we also allow for formatting variations, where incode and outcode may be separated by zero, one, or multiple [space]
characters:
/^(((([A-Z][A-Z]{0,1})[0-9][A-Z0-9]{0,1}) {0,}[0-9])[A-Z]{2})$/
➜ See a demo on regex101.
This matches, in order:
You may find it more convenient to match elements individually, in which case you just need to rearrange the parenthesis.
This example matches all possible elements, and also includes the i
modifier to allow for upper and lower case letters:
/^(([A-Z][A-Z]{0,1})([0-9][A-Z0-9]{0,1})) {0,}(([0-9])([A-Z]{2}))$/i
➜ See a demo on regex101.
This matches, in order:
You can use one of the parsing regular expressions above to validate that a string meets the correct format for a UK postcode.
However, this does not mean that the string matches an actual postcode!
The only safe check you can do here, is to look the postcode up in a current postcode database.
The open data database is the Ordnance Survey's Code-Point Open. This is sufficient for most purposes.
More comprehensive and regularly updated is the Royal Mail's Postcode Address File (PAF). However PAF is not open, and is subject to a license fee.