0

In my app before I send a string off I need to work out if the text entered in the textbox is a UK Postcode. I don't have the regex ability to work that out for myself and after searching around I can't seem to work it out! Just wondered if anyone has done a similar thing in the past?

Or if anyone can point me in the right direction I would be most appreciative!

Tom

MissCoder87
  • 2,669
  • 10
  • 47
  • 82

4 Answers4

3

Wikipedia has a good section about this. Basically the answer depends on what sort of pathological cases you want to handle. For example:

An alternative short regular expression from BS7666 Schema is:

[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}

The above expressions fail to exclude many non-existent area codes (such as A, AA, Z and ZY).

Basically, read that section of Wikipedia thoroughly and decide what you need.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

for post codes without spaces (e.g. SE19QZ) I use: (its not failed me yet ;-) )

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

if spaces (e.g. SE1 9QZ) , then:

^([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})$
Nik Burns
  • 3,363
  • 2
  • 29
  • 37
1

You can match most post codes with this regex:

/[A-Z]{1,2}[0-9]{1,2}\s?[0-9]{1,2}[A-Z]{1,2}/i

Regular expression visualization

Which means... A-Z one or two times ({1,2}) followed by 0-9 1 or two times, followed by a space \s optionally ? followed by 0-9 one or two times, followed by A-Z one or two times.

This will match some false positives, as I can make up post codes like ZZ00 00ZZ, but to accurately match all post codes, the only way is to buy post code data from the post office - which is quite expensive. You could also download free post code databases, but they do not have 100% coverage.

Hope this helps.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

Wikipedia has some regexes for UK Postcodes: http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation

David Brigada
  • 594
  • 2
  • 10