Forum: Ruby Regex: except when

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
basi_lio (Guest)
on 2005-12-03 10:26
(Received via mailing list)
Hello,
I haven't grokked how to include an exception to a condition in a
regular expression. For example, I can't express this correctly:

aString matches if it has a sequence of 3 or more consonants, except
when the consonants [ng] is in the sequence (in that order, n followed
by g).

Thus: plants will match, but bangking will not match.

Thanks for the help,
basi
jeff (Guest)
on 2005-12-03 10:38
(Received via mailing list)
basi wrote:
> Hello,
> I haven't grokked how to include an exception to a condition in a
> regular expression. For example, I can't express this correctly:
>
> aString matches if it has a sequence of 3 or more consonants, except
> when the consonants [ng] is in the sequence (in that order, n followed
> by g).
>
> Thus: plants will match, but bangking will not match.

You might find negative look-ahead helpful.  For example:

consonant = '[bcdfghjklmnpqrstvwxyz]'
r = /#{consonant}{3,}(?!.*ng)/

print "plants: ", r =~ "plants", "\n"
print "bangking: ", r =~ "bangking", "\n"
basi_lio (Guest)
on 2005-12-03 11:10
(Received via mailing list)
Thanks much! I haven't tried it yet, but it looks so elegant it must
work.
basi
jeff (Guest)
on 2005-12-03 11:22
(Received via mailing list)
basi wrote:
> Thanks much! I haven't tried it yet, but it looks so elegant it must
> work.

One thing I screwed up:  If you want to avoid strings that contain ng
*anywhere,* do the negative look-ahead before you match the consonants:


consonant = '[bcdfghjklmnpqrstvwxyz]'
r = /(?!.*ng)#{consonant}{3,}/
basi_lio (Guest)
on 2005-12-03 18:20
(Received via mailing list)
Yes, this one catches initial and final occurences as well. Much
appreciated.
basi
This topic is locked and can not be replied to.