RegExLib.com - The first Regular Expression Library on the Web!

Please support RegExLib Sponsors

Sponsors

Expressions by User

   Displaying page 1 of 1 pages; Items 1 to 2
Title Test Details Pattern Title
Expression
(((^[BEGLMNS][1-9]\d?) | (^W[2-9] ) | ( ^( 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[AEGKL-PRSTWY] | T[ADFNQRSW] | UB | W[ADFNRSV] | YO | ZE ) \d\d?) | (^W1[A-HJKSTUW0-9]) | (( (^WC[1-2]) | (^EC[1-4]) | (^SW1) ) [ABEHMNPRVWXY] ) ) (\s*)? ([0-9][ABD-HJLNP-UW-Z]{2})) | (^GIR\s?0AA)
Description
Here it is, the monster UK Postcode regular expression that should prevent the majority of miskeying. Unlike an most other regexes it only permits valid combinations of letters, e.g. BN works, BM does not. Spaces between the first and second parts are optional. I have tested this against a file of 7,500 valid postcodes, and also against a real-world list of about 12,000 which had some bad data. Manually checking a sample of the rejected ones showed it was working correctly (and how poor the data was!!). I originally started by trying to adapt the GDSC document at http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm and specifically their XSD pattern at http://www.govtalk.gov.uk/gdsc/schemaHtml/bs7666-v2-0-xsd-PostCodeType.htm but this turned out to be rather loose. Instead I wrote this. If you find any valid postcodes being rejected by this regex please let me know.
Matches
W1A 1AA | EC2V 1JN | GIR 0AA
Non-Matches
TB12 1AB | EC2V 1JM | W2A 1AA
Author Rating: The rating for this expression. Howard Richards
Title Test Details Pattern Title
Expression
(((^[BEGLMNS][1-9]\d?)|(^W[2-9])|(^(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[AEGKL-PRSTWY]|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)\d\d?)|(^W1[A-HJKSTUW0-9])|(((^WC[1-2])|(^EC[1-4])|(^SW1))[ABEHMNPRVWXY]))(\s*)?([0-9][ABD-HJLNP-UW-Z]{2}))$|(^GIR\s?0AA$)
Description
For the terminally hard of thinking, a version of my UK postcode validator without WHITESPACE. Unlike most validators on regexlib, this knows valid postcode combinations, e.g. W1A is permitted, W1 is not, but W2 is. It should catch between 95-98% of invalid postcodes.
Matches
W1A 1AA | EC1V1JN | N7 8BQ
Non-Matches
W1A 1AM | BM1 1AB | EC1 1AA
Author Rating: The rating for this expression. Howard Richards
   Displaying page 1 of 1 pages; Items 1 to 2

Copyright © 2001-2024, RegexAdvice.com | ASP.NET Tutorials