Third_Hyperion
Third_Hyperion

Reputation: 467

Complex Regex Pattern for Postcodes

I currently have a regex pattern to only allow 'LL' UK postcodes and I use it with parsley JS with the 'pattern' tag.

data-parsley-pattern="/^[L]{2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/"

I now need to have a complex regex that would allow all 'LL' postcodes and certain 'CH' postcodes.

Can someone please tell me what this would look like? It's way too complex for me.

CH1 6B <---- 1 letter after the B
CH1 6Q <---- 1 letter after the Q
CH4 9A <---- 1 letter after the 0
CH4 9B <---- 1 letter after the 0
CH4 0 <---- 2 letters after the 0
CH5 <---- All variations like the 'LL'regex  [0-9][0-9A-Z]? ?[0-9][A-Z]{2}
CH6 <---- All variations like the 'LL' regex  [0-9][0-9A-Z]? ?[0-9][A-Z]{2}
CH7 <---- All variations like the 'LL' regex  [0-9][0-9A-Z]? ?[0-9][A-Z]{2}
CH8 <---- All variations like the 'LL' regex  [0-9][0-9A-Z]? ?[0-9][A-Z]{2}

The idea is if the postcode starts with 'LL' carry on using the normal regex, if the postcode starts with CH use a different pattern for everything after 'CH'

Is this even possible?

Upvotes: 2

Views: 91

Answers (2)

ZPiDER
ZPiDER

Reputation: 4412

I don't exactly get what the CH-expression should be but maybe i can give you some pointers.

/^(LL\d[0-9A-Z]? ?\d[A-Z]{2}|CH1 (6B|6Q)[0-9A-Z]|CH[2-9] \d[0-9A-Z]{1,2})$/

/^(A|B)$/ will match either A or B. A and B may be more complex as well. You can use that to check for multiple different patterns, each separated with a |.

[L]{2} is a badly legible LL, keep it simple :)

\d is a shorthand for [0-9]

Upvotes: 2

JvdV
JvdV

Reputation: 75840

I have only just started with RegEx (so this could be flawed) but maybe something along these lines:

^(LL\d[0-9A-Z]? ?\d[0-9A-Z]{2}|CH1 (6B|6Q)[A-Z]|CH4 (9A|9B)[A-Z]|CH4 0[A-Z]{2}|CH[5-8][0-9A-Z]? ?\d[0-9A-Z]{2})$

Upvotes: 2

Related Questions