How do I search for 'bar' that is not preceded by 'foo'?
Answer
/foo\@<!bar
Explanation
Vim regex supports zero-width assertions, so you can match text based on context without consuming the context itself. Negative look-behind is useful when a token is valid almost everywhere, but should be ignored after one specific prefix. This gives you safer navigation and cleaner substitutions in noisy code or logs.
How it works
/foo\@<!bar
foois the prefix you want to reject\@<!is Vim's negative look-behind atombaris the text you actually want to match
The engine checks the prefix position and only matches bar when foo is not immediately before it. Because the assertion is zero-width, only bar is selected.
Example
Input
foobar
xxbar
bar
myfoobar
Pattern
/foo\@<!bar
Matches
xxbar
bar
Non-matches
foobar
myfoobar
Tips
- Combine this with
:vimgrepor:globalwhen you need context-aware filtering - Keep it explicit before optimizing with very-magic syntax like
\v - If you need more complex context rules, build and test the pattern incrementally