Is it possible to create a regex to match a line that contains one word but not another?
regex
Solution
Here is a fairly straightforward way to do this:
^(?!.*\bbar\b).*\bfoo\b.*
Explanation:
^ # 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` in regex is a word boundary.
Vim version:
^\(.*\<bar\>\)\@!.*\<foo\>.*
Problem
Similar questions have been asked, but none answer this specific question. Given this representative text: ``` foo bar foo bar bar foo foo bar foo bar foo bar ``` Is it possible to use regular expressions to match only lines that do contain the word `foo` but don't contain the word `bar`? If this desired regular expression was run on the above text, it would only result in: ``` foo ```