Ruby Regex: rejecting whole words

I know that in Regex you can reject lists of characters, like [^abc] . I would like to refuse to view the whole word in the middle of the input.

To be more precise, I would 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 
+7
source share
2 answers

You are looking for a negative outlook . (link using look-ahead and look-behind )

 (?!exclude) 

Will disqualify the word โ€œexcludeโ€ in the template.

+11
source

Regular expressions support breaking the word \b .

Finding the existence of the word โ€œeverythingโ€ 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 that he did not bind it to the beginning or end of the line, because \b also recognizes the beginning and end of the line as word boundaries.

+2
source

All Articles