1

I'm trying to validate UK zip codes in Ruby. I stumbled upon this regex on stackoverflow:

(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})

It works great in Ruby 1.9.2 and 2.0.0 (see http://rubular.com/r/GKgLdIFvNJ) but I'm working with 1.8.7. What can I do?

Any suggestion would be appreciated. Thanks!

stema
  • 90,351
  • 20
  • 107
  • 135
Akki209
  • 123
  • 12

1 Answers1

2

Where did you find this expression? I assume it was not written for Ruby.

Ruby is not supporting character class subtraction. So 1.9.2 is accepting [A-Z-[QVX]] but is not working as expected. Those characters are not excluded from the char class (See rubular, QVX is still matched)

1.8.7 is not accepting this expression at all.

You have to rewrite all those character ranges like this:

[A-Z-[QVX]] becomes [A-PR-UWYZ]

See on Rubular

stema
  • 90,351
  • 20
  • 107
  • 135
  • Thanks worked like a charm!! PS: I hate working on 1.8.7 just bcoz these silly reasons!! – Akki209 May 06 '14 at 08:51
  • You are welcome, but I think the behaviour of 1.8.7 is better here IMO. From 1.9.2 they accept the pattern, **but it is not interpreted as you expect**. – stema May 06 '14 at 09:00