Search code examples
regexpostal-code

Regular Expression for England only Postcode


I have an Asp.Net website and I want to use a RegularExpressionValidator to check if a UK postcode is English (i.e. it's not Scottish, Welsh or N.Irish).

It should be possible to see if the postcode is English by using just the letters from the first segmant (called the Postcode Area). In total there are 124 postcode areas and this is a list of them.

From that list, the following postcode areas are not in England.

  • ZE,KW,IV,HS,PH,AB,DD,PA,FK,G,KY,KA,DG,TD,EH,ML (Scotland)
  • LL,SY,LD,HR,NP,CF,SA (Wales)
  • BT (N.Ireland)

The input to the regex may be the whole postcode, or it might just be the postcode area.

Can anyone help me create a regular expression that will match only if a given postcode is English?

EDIT - Solution

With help from several posters I was able to create the following regex which i've tested against over 1500 testcases successfully.

^(AL|B|B[ABDHLNRS]|C[ABHMORTVW]|D[AEHLNTY]|E|E[CNX]|FY|G[LUY]|H[ADGPUX]|I[GM‌​P]‌​ |JE|KT|L|L[AENSU]|M|ME|N|N[EGNRW]|O[LX]|P[ELOR]|R[GHM]|S|S[EGKLMNOPRSTW]|T[AFNQ‌​‌​ RSW]|UB|W|W[ACDFNRSV]|YO)\d{1,2}\s?(\d[\w]{2})?


Solution

  • There are 124 Postcode Areas in the UK.

    -- PAF® statistics August 2012, via List of postcodes in the United Kingdom (Wikipedia).

    I recommend breaking your problem down into two parts (think functions):

    1. Is the postcode valid?

      UK Postcode Regex (Comprehensive)

    2. Is the postcode English?

      This can be broken down further:

      • Not Scottish:
        • ! /^(ZE|KW|IV|HS|PH|AB|DD|PA|FK|G|KY|KA|DG|TD|EH|ML)[0-9]/
      • Not Welsh:
        • ! /^(LL|SY|LD|HR|NP|CF|SA)[0-9]/
      • Not Northern Irish, Manx, from the Channel Islands, ...
        • et cetera...
      • or you could just check that the Postcode Area is among the hundred or so English ones, depending on how you want to optimise ☻

    Note that the syntax will vary according to your programming language. Doing all this in one regular expression would soon become unmanageable.