Postcode Regular Expression

The following regular expression can be used to validate UK postcodes. I'm posting this here as I can never find it when I need it.

^(([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}))$

It is not case sensitive. It matches postcodes starting GIR which are for GiroBank which may not be required.


Re: Postcode Regular Expression

To change the expression to allow postcodes with no space in the middle you need to put {0,1} after the space giving you this:

^([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,1}[0-9][A-Za-z]{2})$

Comment from Martin Brown at Saturday, 27 January 2007 12:13PM (GMT+00)

Re: Postcode Regular Expression

Desperately needed one of these for a project I'm working on. Cheers! Works a treat (i'm using it Access)

Comment from Anon at Thursday, 10 May 2007 12:28AM (GMT+00)

Re: Postcode Regular Expression

You might be interested in this:

[a-zA-Z]{1,2}[0-9][0-9A-Za-z]? [0-9][a-zA-Z]{2}

and you should be okay for:

"A9 9AA", "A99 9AA", "AA9 9AA", "AA99 9AA", "A9A 9AA" or "AA9A 9AA",


Comment from Alex at Friday, 31 August 2007 08:13PM (GMT+00)

Re: Postcode Regular Expression

Alex you are the genius. Keep It Simple Stupid (KISS).
Used it on my project actually!
This first one works but very, very long.

Comment from Arthur Massally at Saturday, 04 July 2009 04:32AM (GMT+00)

Re: Postcode Regular Expression

Your simple regex does not work for this valid London postcode Alex :


Therefore go with Martin Browns' works a treat :)

Comment from Jamin at Thursday, 10 June 2010 03:45PM (GMT+00)

Re: Postcode Regular Expression

This is how you use the above regular expression in PHP code.

public function is_uk_postcode($postcode)
return preg_match('/^(([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}))$/ui', $postcode);

Comment from Hani Weiss at Thursday, 12 January 2012 12:47PM (GMT+00)

Sorry, this post is no longer accepting comments.