I’m trying to write a Regex in Ruby for a shipping query.
If postcodes match MK1 – MK10, MK19, MK43, MK46 or MK77, then allow it.
If postcodes match NN1 – NN7, NN12, NN13, NN29 or NN77, then allow it.
If postcodes match MK11 – MK18 then don’t allow it.
My trouble is that in the UK our postcodes are a bit funny where you can put MK1 1TS and MK11TS and they’re considered the same. By not allowing MK11, MK11TY could be misread as MK11.
I’ve written a regex below, and so far it will disallow MK111TS and MK11s1TS, and allow MK1s1TS but not MK11TS. Any help would be greatly appreciated, I’ve only tested this for MK11 so far.
^((?!MK11d).)*$&^((?!MK11sd).)*$|(MK(1 |2 |3 |4 |5 |6 |7 |8 |9 |10 ))|(MK19)|(MK43)|(MK46)|(MK77)|(NN1)|(NN2)|(NN3)|(NN4)|(NN5)|(NN6)|(NN7)|(NN12)|(NN13)|(NN29)|(NN77)
Thanks in advance.
2
Answers
Now I have written the following to match the postcodes format exactly:
This works for my purposes, I got here using Cary's answer, which has been extremely helpful. Thank you and have marked up.
This is conventionally written
"MK11"
is not matched because"11"
is not in the list."MK19"
is not matched because it is followed by a character that is neither a space nor a capital letter.Alternatively, one could write
If the remainder of the postal code is to be included in the regex, perhaps something like the following could be done.
Then replace
(?![^sA-Z])/x
with the following.Note the negative lookahead is satisfied if the suffix is at the end of the string.