Ruby正则表达式:拒绝整个单词

7
我知道在正则表达式中,你可以拒绝符号列表,例如[^abc]。我想在输入的中间看到整个单词时进行拒绝。
更准确地说,我想拒绝“print <除了“all”之外的任何内容>”。 一些例子:
print all - match
frokenfooster - no match
print all nomnom - no match
print bollocks - no match
print allpies - no match

我觉得“我想匹配”和你提供的例子是矛盾的。 - Brad Christie
2个回答

12

@Mike:附言,我认为你正在寻找 ^print ((?!all$).*)$ ;-) - Brad Christie
错过了锚点。现在看起来很牢固。 :) - Mike
如果“excluded”在一行的中间,这样做不也会使其失效吗? - the Tin Man
@theTinMan:是的,这就是为什么你必须要进行封装。 - Brad Christie

2

正则表达式支持单词分界符 \b

在字符串中搜索单词 "all" 的存在就像这样简单:

>> '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"

请注意,这里不需要将其锚定到字符串的开头或结尾,因为\b也会识别字符串的开头和结尾作为单词边界。


我不知道那个 - 那真的很方便。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接