How do I refer to the matched text in a Vim substitution replacement?
Answer
:%s/\w\+/(&)/g
Explanation
In a Vim substitution, & in the replacement string expands to the entire matched text. This lets you wrap, annotate, or transform every match without capture groups — making operations like quoting identifiers, adding markup, or surrounding keywords much simpler.
How it works
&expands to the full text matched by the pattern- It works in
:sand in the~(repeat-last-substitution) command \0is a synonym for&in Vim's replacement syntax- To insert a literal
&in the replacement, escape it:\&
:%s/\btodo\b/[&]/gi " wrap every TODO in brackets
:%s/^.*$/> &/ " prefix every line with '> ' (email-style quote)
:%s/\w\+/"&"/g " double-quote every word
Example
Given:
hello world
Running :%s/\w\+/(&)/g produces:
(hello) (world)
Each word is wrapped in parentheses — no capture groups needed.
Tips
- Combine with case modifiers:
:%s/\w\+/\u&/gcapitalizes every word \L&\Elowercases the match,\U&\Euppercases it entirely&also works with:s///cconfirmation — you see the highlighted match before each replacement- In the replacement,
~by itself repeats the last used replacement string (not to be confused with&)