How do I use capture groups to rearrange text in a Vim substitute command?
Answer
:%s/\(pattern1\)\(pattern2\)/\2\1/g
Explanation
Vim's substitute command supports capture groups that let you match parts of text, remember them, and rearrange or reuse them in the replacement. Wrap parts of your search pattern in \( and \) to capture them, then reference them in the replacement with \1, \2, etc.
How it works
\(and\)define a capture group in the search pattern- Each group is numbered left to right, starting at
\1 - In the replacement,
\1inserts the text matched by the first group,\2the second, and so on \0or&refers to the entire match, not just a group- You can have up to 9 capture groups (
\1through\9)
Example
Swap first and last names:
:%s/\(\w\+\) \(\w\+\)/\2 \1/g
Given the text:
John Smith
Jane Doe
Bob Johnson
The result is:
Smith John
Doe Jane
Johnson Bob
Another example — convert width: 100px to width: 100rem:
:%s/\(\d\+\)px/\1rem/g
Turns margin: 16px 24px into margin: 16rem 24rem.
Tips
- In very magic mode (
\v), you don't need backslashes on the parens::%s/\v(\w+) (\w+)/\2 \1/g - Use
\_.\+instead of.\+if you need a group to match across line boundaries - Non-capturing groups are not natively supported in Vim regex, but you can use
\%( \)to group without capturing — useful for alternation without consuming a group number - Combine with
\=for expression replacements::%s/\(\d\+\)/\=submatch(1)*2/gdoubles every number - Capture groups work in search patterns too —
\1in a search backreferences the first group, useful for finding repeated words:/\(\w\+\) \1 - Always test complex substitutions with the
cflag first (/gc) to confirm each replacement interactively before committing