How do I swap or rearrange text using captured groups in Vim substitution?
Answer
:%s/\(\w\+\) \(\w\+\)/\2 \1/g
Explanation
Vim's substitute command supports captured groups (back-references) using \( and \), allowing you to capture parts of a match and rearrange them in the replacement. This is one of the most powerful text transformation techniques in Vim.
How it works
\(pattern\)— captures the matched text into a numbered group\1,\2, etc. — refers to the captured groups in the replacement- Groups are numbered left-to-right by their opening parenthesis
- Up to 9 groups (
\1through\9) are supported
Example
Swap first and last names:
:%s/\(\w\+\) \(\w\+\)/\2 \1/g
Before: John Smith
After: Smith John
Reformat a date:
:%s/\(\d\{4}\)-\(\d\{2}\)-\(\d\{2}\)/\3\/\2\/\1/g
Before: 2024-01-15
After: 15/01/2024
Tips
- Use
\v(very magic) for cleaner syntax::%s/\v(\w+) (\w+)/\2 \1/g \0or&refers to the entire match- Non-capturing groups
\%(pattern\)group without capturing, preserving group numbers