views:

66

answers:

4

I want to validate a field with a UK Post Code. What regular expression could be used to validate this field?. (([A-Z]{1,2}[0-9][0-9A-Z]{0,1})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$ does appear valid because it has the exception GIR 0AA.

So, please help me to write an expression without any exception

A: 

(([A-Z]{1,2}[0-9][0-9A-Z]{0,1})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$ this expression i have taken from regexlib please help me to write new expressions

ansar hussain
A: 
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
+1  A: 

If you do mean post code, wikipedia has a section on validation. One regex that it recommends is:

((A[BL]|B[ABDHLNRST]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|([E|N|NW|SE|SW|W]1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|[SW|W]([1-9][0-9]|[2-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2}

The advantage of this one is that it catches some invalid areas and districts.

John McCollum
A: 

Side note: GIR 0AA is listed as an exception in your regular expression because it is a valid UK post code for what are esentially historical reasons (search for it in the Wikipedia article, it's given special mention).

There is no trivial regular expression you can write to validate a UK post code as there's no surety that, for example, GU78 2AB is valid (the GU78 outward area may only contain 2A*A*, but not 2A*B*), whereas GU77 2AB may well be considered valid.

You can use a regular expression to validate the form and structure of a piece of text to determine if it matches the requirements to be considered a post code. I believe that, broadly speaking, the following regular expression will satisfy that:

(([A-Z]{1,2}[0-9]{1,2})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$
Rob
Thanks for the response this really helped me a lot, I thought that was an exception now i understand it means
ansar hussain