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
\venables very magic mode: metacharacters like(,),+work without escaping(\w+)captures one or more word characters as group 1matches a literal space between the two words(\w+)captures the second word as group 2\2 \1in 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 (\uuppercases the next char) - For complex transforms, use
\=withsubmatch()::s/\v(\d+)/\=submatch(1)*2/gdoubles every number on the line - Visual select lines first (
V) then:sto limit the substitution to those lines