How do I search using lookahead and lookbehind patterns in Vim?
Answer
/pattern\@<=match
Explanation
Vim supports zero-width assertions (lookahead and lookbehind) in its regex engine, allowing you to match text based on what precedes or follows it without including the surrounding text in the match. This is invaluable for advanced search-and-replace operations where you need precise context matching.
How it works
\@<=— positive lookbehind: match only if preceded bypattern\@<!— negative lookbehind: match only if NOT preceded bypattern\@=— positive lookahead: match only if followed bypattern\@!— negative lookahead: match only if NOT followed bypattern
The syntax places the assertion after the pattern it refers to, which differs from Perl-style regex.
Example
To find bar only when preceded by foo:
/foo\@<=bar
To find bar only when NOT followed by baz:
/bar\(baz\)\@!
Before: foobar foobaz quxbar
Search /foo\@<=bar highlights: foobar (only the 'bar' part)
Tips
- Combine with
:sfor precise substitutions::%s/foo\@<=bar/BAR/greplacesbaronly afterfoo - Use
\zsand\zeas simpler alternatives when you just need to shift match boundaries - These atoms work with Vim's
\v(very magic) mode too:/\v(foo)@<=bar