Frage

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!

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top