vimtricks.wiki Concise Vim tricks, one at a time.

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 by pattern
  • \@<! — negative lookbehind: match only if NOT preceded by pattern
  • \@= — positive lookahead: match only if followed by pattern
  • \@! — negative lookahead: match only if NOT followed by pattern

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 :s for precise substitutions: :%s/foo\@<=bar/BAR/g replaces bar only after foo
  • Use \zs and \ze as simpler alternatives when you just need to shift match boundaries
  • These atoms work with Vim's \v (very magic) mode too: /\v(foo)@<=bar

Next

How do I return to normal mode from absolutely any mode in Vim?