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

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 :s and in the ~ (repeat-last-substitution) command
  • \0 is 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&/g capitalizes every word
  • \L&\E lowercases the match, \U&\E uppercases it entirely
  • & also works with :s///c confirmation — you see the highlighted match before each replacement
  • In the replacement, ~ by itself repeats the last used replacement string (not to be confused with &)

Next

How do I see all recent Vim messages, errors, and echo output I may have missed?