Regexp: how to validate a UK Postcode

In the UK, postcodes are a crucial part of someone’s address, as they narrow addresses down to the street of the desired location (in countries like France, however, a postcode only tells you which city or town the address is located).
It can be handy to make sure your users provide a valid UK postcode in a form. To do this, we’ll need to match the postcode to a regexp… but what is a valid UK postcode, and what regexp can we use to make sure a postcode is indeed valid ?

Wikipedia tells us UK postcodes can use the following formats (‘A’ stands for any letter, and ‘9’ for any digit):

Format Coverage Example
AA9A 9AA WC postcode area; EC1–EC4, NW1W, SE1P, SW1 EC1A 1BB
A9A 9AA E1W, N1C, N1P W1A 0AX
A9 9AA B, E, G, L, M, N, S, W M1 1AE
A99 9AA B33 8TH
AA9 9AA All other postcodes CR2 6XH
AA99 9AA DN55 1PT

To match any of these patterns, we can use the following regular expression:


Let’s decompose this so we know what it’s doing:

  • We start by making sure our postcode isn’t surrounded by anything else in our field, so we encase it between a beginning of input boundary (^) and an end of input boundary ($).
  • Then, we accept one or two letters [a-zA-Z]{1,2}
  • Followed by either one digit and a letter, or between one and two digits: ([0-9]{1,2}|[0-9][a-zA-Z])
  • An optional space \s*
  • Finally, a digit followed by two letters: [0-9][a-zA-Z]{2}

What have I missed? Is there a better way to write this? How hard is it to get UK addresses from a postcode using an external API? Let me know !