How do I match text only when it is preceded by a specific pattern in Vim regex?
Answer
:%s/\(prefix\)\@<=target/replacement/g
Explanation
Vim's \@<= is a zero-width look-behind assertion. It requires the preceding group to match at the current position but does not consume any characters — so only target is matched and substituted while the prefix is left intact.
The general form is:
:%s/\(prefix\)\@<=target/replacement/g
How it works
\(prefix\)— the look-behind group: text that must appear immediately before the match\@<=— asserts that the look-behind group precedes the current position (zero-width: not included in the match)target— the actual pattern to match and replace
In very magic mode (\v), escaping is reduced: \v(prefix)\@<=target
Example
Given:
function foo
function bar
var baz
To rename only identifiers after function , leaving var baz untouched:
:%s/\(function \)\@<=\w\+/handler/g
Result:
function handler
function handler
var baz
The prefix function is preserved; only the word following it was replaced.
Tips
\@<!— negative look-behind: match text that is not preceded by a pattern.\@=/\@!— look-ahead and negative look-ahead assertions.- Very magic reduces escaping:
\v(function )\@<=\w+ - Unlike PCRE, Vim allows variable-length patterns in look-behind groups.