开发者

Ruby Regex: Rejecting whole words

开发者 https://www.devze.com 2023-02-08 09:02 出处:网络
I know that in Regex, you can r开发者_如何学JAVAeject lists of symbols, such as [^abc]. I\'d like to reject upon seeing an entire word in the middle of my input.

I know that in Regex, you can r开发者_如何学JAVAeject 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


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

(?!exclude)

Would disqualify the word "exclude" in the pattern.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号