开发者

Reguar Expression, UK Post Code, Slight Amendment?

I use the regular expression:

^(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|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)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})$

to correctly validate a uk post code which can generally (there are exceptions) be any one of the following formats:

A9 9AA

A99 9AA

AA9 9AA

AA99 9AA

A9A 9AA

AA9A 9AA

I want to change my expression so that it will allow either a correct whole post code (as it does now) or a correct "first part" of the post code only.. so using one of the above examples:

A开发者_Python百科A9 would be a valid format

AA9 9AA would be a valid format

AA would be invalid

AA9 9 would be invalid

Thanks in avance,

Jim


It looks like there are many more optimizations available, but this depends on the complexity of the code...

This is a slight modification of yours:

^(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|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)([2-9]|[1-9][0-9])|EC[1-9][0-9])( [0-9][ABD-HJLNP-UW-Z]{2})?)$

As you can see, the ? makes the last part optional

 [0-9][ABD-HJLNP-UW-Z]{2})$
( [0-9][ABD-HJLNP-UW-Z]{2})?)$

Modifying aadravid's simpler version (If you want a less strict one)

'/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]?( [0-9][ABD-HJLNP-UW-Z]{2})?\\b\\z/i'


I use this from the cakephp framework and works for me...

'/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜