是否可以创建一个正则表达式来匹配包含一个单词而不是另一个单词的行?

问题描述:

Similarquestionshavebeen问,但没有人回答这个问题。是否可以创建一个正则表达式来匹配包含一个单词而不是另一个单词的行?

鉴于这种代表性的文字:

foo 
bar 
foo bar 
bar foo 
foo bar foo 
bar foo bar 

是否可以使用正则表达式匹配只有那些包含单词foo,但不包含单词bar线?

如果需要的正则表达式是在上面的文字运行时,它只会导致:

foo 

这里是要做到这一点相当简单的方法:

^(?!.*\bbar\b).*\bfoo\b.* 

说明:

^    # starting at beginning of the string 
(?!    # fail if (negative lookahead) 
    .*\bbar\b  # the word 'bar' exists anywhere in the string 
)    # end negative lookahead 
.*\bfoo\b.*  # match the line with the word 'foo' anywhere in the string 

Rubular:http://www.rubular.com/r/pLeqGQUXbj

\b在正则表达式是一个word boundary

Vim的版本:

^\(.*\<bar\>\)\@!.*\<foo\>.* 
+1

+1 - 这是一个比我更好的解决方案。 – 2012-07-10 19:51:19

+0

任何人都想成为我的英雄,并以'vim'接受的形式呈现这个正则表达式? – 2012-07-10 19:57:17

+1

@CoryKlein - 用Vim版本编辑我的答案。 – 2012-07-10 20:01:42

是。使用lookarounds。

/^.*(?<!\bbar\b.*)\bfoo\b(?!.*\bar\b).*$/