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

How do I use capture groups in Vim substitutions to rearrange or swap matched text?

Answer

:s/\v(\w+) (\w+)/\2 \1/

Explanation

Vim's substitute command supports capture groups using \( and \) (or ( and ) in \v very-magic mode). Each group is referenced in the replacement as \1, \2, etc. This lets you reorder, combine, or transform parts of a match without re-typing the captured text.

How it works

  • \v enables very magic mode: metacharacters like (, ), + work without escaping
  • (\w+) captures one or more word characters as group 1
  • matches a literal space between the two words
  • (\w+) captures the second word as group 2
  • \2 \1 in the replacement swaps their order

Without \v, the same pattern requires extra escapes: :s/\(\w\+\) \(\w\+\)/\2 \1/

Example

Given the line:

John Smith

Running :s/\v(\w+) (\w+)/\2, \1/ produces:

Smith, John

Or swap two adjacent words across the whole buffer with :%s/\v(\w+) (\w+)/\2 \1/g.

Tips

  • Use \0 (or &) to reference the entire match in the replacement
  • Combine with :s/\v.../\u\1/ to capitalize the first capture group (\u uppercases the next char)
  • For complex transforms, use \= with submatch(): :s/\v(\d+)/\=submatch(1)*2/g doubles every number on the line
  • Visual select lines first (V) then :s to limit the substitution to those lines

Next

How do I add or remove words from Vim's spell check dictionary?