Regex: except when

B

basi

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
 
J

Jeffrey Schwab

basi said:
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"
 
J

Jeffrey Schwab

basi said:
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,}/
 
B

basi

Yes, this one catches initial and final occurences as well. Much
appreciated.
basi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top