This question already has an answer here:
- UK Postcode Regex (Comprehensive) 28 answers
I'm looking to be able to validate UK Postcodes, and ideally, I would like the following cases to pass:
- W1
- W12
- WC1
- WC1A
- WC12
- W1 6BT
- W12 6BT
- WC1 6BT
- WC1A 6BT
- WC12 6BT
- W16BT
- W126BT
- WC16BT
- WC1A6BT
- WC126BT
I have the following regex patterns:
^(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})?)$
This pattern allows for 3 or 4 & 6 or 7 digit postcodes (so either outward code only with 3 or 4 digits, or full postcodes with 6 or 7 digits) however it doesn't allow for points 4 and 6 (postcodes where spaces have been omitted)
I also have this pattern:
^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW]) {0,1}[0-9][ABD-HJLNP-UW-Z]{2})$
This pattern allows for 6 or 7 digit postcodes, with our without the space, but not for incomplete postcodes (outward code only)
Sorry for asking a question that has been covered so extensively already on here, but all the examples I found, they match part of my requirement, but not all of it.
Ideally, I'd like a regex pattern that allows 3, 4, 6 & 7 digit postcodes, with our without spaces.
UPDATE:
I've re done my pass cases as I don't think it was entirely comprehensive initially. The basic concept that is it should follow UK postcode patterns, and validate any of the following combinations:
1 Letter 1 Number 1 Letter 2 Numbers 2 Letters 1 Number 2 Letters 1 Number 1 Letter 2 Letters 2 Numbers 1 Letter 1 Number (OptionalSpace) 1 Number 2 Letters 1 Letter 2 Numbers (OptionalSpace) 1 Number 2 Letters 2 Letters 1 Number (OptionalSpace) 1 Number 2 Letters 2 Letters 1 Number 1 Letter (OptionalSpace) 1 Number 2 Letters 2 Letters 2 Numbers (OptionalSpace) 1 Number 2 Letters
^ Hope the above makes sense, and is detailed enough. Bit hard to read I know.
ANSWER:
So I now have a regex that passes all the cases above (example and pattern). As mentioned in the comment below, it's very hard, if not impossible to cater for ALL UK postcodes, nevertheless, the one below does all I need and should be good for 90% of input cases:
^(GIR 0AA)|[a-z-[qvx]](?:\d|\d{2}|[a-z-[qvx]]\d|[a-z-[qvx]]\d[a-z-[qvx]]|[a-z-[qvx]]\d{2})(?:\s?\d[a-z-[qvx]]{2})?$