开发者

Validating UK Post Codes using regular expressions

I want to validate a field with a UK Post Code. What regular expression could be used to valida开发者_运维问答te 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


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.


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 2AA, but not 2AB), 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)$


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜