Search code examples
regexsearchvimregular-language

Vim search pattern 'foo' but skip lines containing 'bar' without deleting any line


I want to use search and highlight in vim using pattern match. My first search criteria is to look for a string foo in a line. My second search criteria is to skip all foo if the same line contains bar in it. I don't want to delete all lines containing bar. My first search criteria meets with following:

/foo

My second criteria is not meeting with:

/foo.*\(bar\)\@<!

Example text:

1 foo
2 foo bar xx
3 fooobar
4 bar
5 xxx

(here I want to highlight line numbers 1 only)

What I am missing here?

Reference: http://vimdoc.sourceforge.net/htmldoc/pattern.html


Solution

  • You may use

    /\(bar.*\)\@<!foo\(.*bar\)\@!
    

    With very magic mode:

    /\v(bar.*)@<!foo(.*bar)@!
    

    Details

    • (bar.*)@<! - a negative lookbehind: no bar followed with any 0 or more characters to the right of the current location
    • foo - a word foo
    • (.*bar)@! - a negative lookahead: no bar allowed after any 0 or more characters to the right of the current location.