3

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
Community
  • 1
  • 1
Cory Klein
  • 51,188
  • 43
  • 183
  • 243

2 Answers2

10

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\>.*
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Yes. Use lookarounds.

/^.*(?<!\bbar\b.*)\bfoo\b(?!.*\bar\b).*$/
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145