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

How do I use look-behind assertions in Vim regex to match text only when preceded by a pattern?

Answer

\@<=

Explanation

The \@<= operator is Vim's zero-width look-behind assertion. It asserts that a pattern precedes the match position without consuming characters — so searches and substitutions operate only on the text after the assertion, leaving the preceding context unchanged. This is invaluable for precision substitutions where you want to replace something that always follows a fixed prefix.

How it works

The syntax is: \(lookbehind\)\@<=text_to_match

  • \(lookbehind\) — the pattern that must precede the cursor position
  • \@<= — zero-width assertion: "this position must be preceded by the group above"
  • text_to_match — what actually gets highlighted or replaced

In very-magic mode (\v), the syntax is cleaner: (lookbehind)@<=text_to_match

Example

You want to rename the function foo only in declarations, not in call sites:

function foo() { return foo(1); }

Run:

:%s/\(function \)\@<=foo/bar/g

Result:

function bar() { return foo(1); }

The second foo (inside the function body) is untouched because it is not preceded by function .

Tips

  • Very-magic equivalent: :%s/\v(function )@<=foo/bar/g
  • Negative look-behind (\@<!) matches when NOT preceded by the pattern
  • For look-ahead use \@= (positive) and \@! (negative)
  • \zs sets the start of the match like a look-behind but works differently with variable-length patterns — \@<= is stricter and more composable
  • Use :help \@<= to see full documentation

Next

How do I trigger a custom user-defined completion function in insert mode?