Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regex: Rejecting whole words

Tags:

regex

ruby

I know that in Regex, you can reject lists of symbols, such as [^abc]. I'd like to reject upon seeing an entire word in the middle of my input.

To be more precise, I'd like to reject "print <Anything except "all">". A few examples:

print all - match
frokenfooster - no match
print all nomnom - no match
print bollocks - no match
print allpies - no match
like image 425
Mike Avatar asked Feb 02 '11 20:02

Mike


2 Answers

You're looking for a negative look-ahead. (ref. using look-ahead and look-behind)

(?!exclude)

Would disqualify the word "exclude" in the pattern.

like image 85
Brad Christie Avatar answered Sep 22 '22 10:09

Brad Christie


Regular expressions support a word-break \b.

Searching for the existence of the word "all" in a string is as simple as:

>> 'the word "all"'[/\ball\b/] #=> "all"
>> 'the word "ball"'[/\ball\b/] #=> nil
>> 'all of the words'[/\ball\b/] #=> "all"
>> 'we had a ball'[/\ball\b/] #=> nil
>> 'not ball but all'[/\ball\b/] #=> "all"

Note, it didn't take anchoring it to the start or end of a string, because \b recognizes the start and end of the string as word boundaries also.

like image 43
the Tin Man Avatar answered Sep 21 '22 10:09

the Tin Man