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.
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[GMP] |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})?
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):
Is the postcode valid?
Is the postcode English?
This can be broken down further:
! /^(ZE|KW|IV|HS|PH|AB|DD|PA|FK|G|KY|KA|DG|TD|EH|ML)[0-9]/
! /^(LL|SY|LD|HR|NP|CF|SA)[0-9]/
Note that the syntax will vary according to your programming language. Doing all this in one regular expression would soon become unmanageable.