I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:
Matches
- CW3 9SS
- SE5 0EG
- SE50EG
- se5 0eg
- WC2H 7LT
No Match
- aWC2H 7LT
- WC2H 7LTa
- WC2H
Are there any official or even semi-official regexes in use for this kind of thing? Any other advice as to formatting and storing these in a database?
This one allows empty spaces and tabs from both sides in case you don't want to fail validation and then trim it sever side.
I recently posted an answer to this question on UK postcodes for the R language. I discovered that the UK Government's regex pattern is incorrect and fails to properly validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.
I'll outline some of these issues below and provide a revised regular expression that actually works.
Note
My answer (and regular expressions in general):
If you don't care about the bad regex and just want to skip to the answer, scroll down to the Answer section.
The Bad Regex
The regular expressions in this section should not be used.
This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their Bulk Data Transfer documentation):
Problems
Problem 1 - Copy/Paste
See regex in use here.
As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:
The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the
GIR 0AA
postcode).To fix this issue, the newline character should be replaced with the space character:
Problem 2 - Boundaries
See regex in use here.
The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like
fooA11 1AA
gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.What this means is that
^
(asserts position at start of the line) only works on the first option([Gg][Ii][Rr] 0[Aa]{2})
, so the second option will validate any strings that end in a postcode (regardless of what comes before).Similarly, the first option isn't anchored to the end of the line
$
, soGIR 0AAfoo
is also accepted.To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that:
Problem 3 - Improper Character Set
See regex in use here.
The regex is missing a
-
here to indicate a range of characters. As it stands, if a postcode is in the formatANA NAA
(whereA
represents a letter andN
represents a number), and it begins with anything other thanA
orZ
, it will fail.That means it will match
A1A 1AA
andZ1A 1AA
, but notB1A 1AA
.To fix this issue, the character
-
should be placed between theA
andZ
in the respective character set:Problem 4 - Wrong Optional Character Set
See regex in use here.
I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made
[0-9]
option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes likeAAA 1AA
.To fix this issue, make the next character class optional instead (and subsequently make the set
[0-9]
match exactly once):Problem 5 - Performance
Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match
GIR 0AA
at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the original regex took (35) against the same regex after having flipped the options (22).The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the Answer section.
Problem 6 - Spaces
See regex in use here
This may not be considered a problem, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding
?
after the spaces to render them optional. See the Answer section for a fix.Answer
1. Fixing the UK Government's Regex
Fixing all the issues outlined in the Problems section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):
See regex in use here
This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. Note: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.
See regex in use here.
Shorter again replacing
[0-9]
with\d
(if your regex engine supports it):See regex in use here.
2. Simplified Patterns
Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from 1. Fixing the UK Government's Regex have also been applied here):
See regex in use here.
And even further if you don't care about the special case
GIR 0AA
:3. Complicated Patterns
I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest potentially doing, is added support for edge-cases. Some special cases exist and are outlined in this Wikipedia article.
Here are complex regexes that include the subsections of 3. (3.1, 3.2, 3.3).
In relation to the patterns in 1. Fixing the UK Government's Regex:
See regex in use here
And in relation to 2. Simplified Patterns:
See regex in use here
3.1 British Overseas Territories
The Wikipedia article currently states (some formats slightly simplified):
AI-1111
: AnguilaASCN 1ZZ
: Ascension IslandSTHL 1ZZ
: Saint HelenaTDCU 1ZZ
: Tristan da CunhaBBND 1ZZ
: British Indian Ocean TerritoryBIQQ 1ZZ
: British Antarctic TerritoryFIQQ 1ZZ
: Falkland IslandsGX11 1ZZ
: GibraltarPCRN 1ZZ
: Pitcairn IslandsSIQQ 1ZZ
: South Georgia and the South Sandwich IslandsTKCA 1ZZ
: Turks and Caicos IslandsBFPO 11
: Akrotiri and DhekeliaZZ 11
&GE CX
: Bermuda (according to this document)KY1-1111
: Cayman Islands (according to this document)VG1111
: British Virgin Islands (according to this document)MSR 1111
: Montserrat (according to this document)An all-encompassing regex to match only the British Overseas Territories might look like this:
See regex in use here.
3.2 British Forces Post Office
Although they've been recently changed it to better align with the British postcode system to
BF#
(where#
represents a number), they're considered optional alternative postcodes. These postcodes follow(ed) the format ofBFPO
, followed by 1-4 digits:See regex in use here
3.3 Santa?
There's another special case with Santa (as mentioned in other answers):
SAN TA1
is a valid postcode. A regex for this is very simply:To check a postcode is in a valid format as per the Royal Mail's programmer's guide:
All postcodes on doogal.co.uk match, except for those no longer in use.
Adding a
?
after the space and using case-insensitive match to answer this question:I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):
/^([a-z0-9]\s*){5,7}$/i
Lengths 5 to 7 (not counting whitespace) means we allow the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET".
EDIT: Changed the 8 to a 7 so we don't allow 8 character postcodes.
It looks like we're going to be using
^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$
, which is a slightly modified version of that sugested by Minglis above.However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.
After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification govtalk-postcodes. This points to an XML schema at XML Schema which provides a 'pseudo regex' statement of the postcode rules.
We've taken that and worked on it a little to give us the following expression:
This makes spaces optional, but does limit you to one space (replace the '&' with '{0,} for unlimited spaces). It assumes all text must be upper-case.
If you want to allow lower case, with any number of spaces, use:
This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:
Can accept the following formats:
Where:
Best wishes
Colin
There is no such thing as a comprehensive UK postcode regular expression that is capable of validating a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.
Postcodes are arbitrarily complex and constantly changing. For instance, the outcode
W1
does not, and may never, have every number between 1 and 99, for every postcode area.You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these.
Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).
Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.
Then, there's the BFPO postcodes, which are now changing to a more standard format. Both formats are going to be valid. Lastly, there's the overseas territories source Wikipedia.
Next, you have to take into account that the UK "exported" its postcode system to many places in the world. Anything that validates a "UK" postcode will also validate the postcodes of a number of other countries.
If you want to validate a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:
Ordnance Survey releases Code-Point Open under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, Pointer product. You could use this and append the few that aren't covered fairly easily.
Royal Mail releases the Postcode Address File (PAF), this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own Programmers Guide. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, here's a description of their position.
Lastly, there's AddressBase. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.