How do I use capture groups in a Vim search and replace?
Answer
:%s/\(group\)/\1/g
Explanation
Capture groups in Vim substitute let you match parts of a pattern and reuse them in the replacement. Groups are created with \( and \) and referenced with \1, \2, etc.
How it works
\(pattern\)creates a capture group\1in the replacement refers to the first group- 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
Wrap words in quotes:
:%s/\(\w\+\)/"\1"/g
Tips
- In very magic mode (
\v), use()without backslashes::%s/\v(\w+) (\w+)/\2 \1/g \0or&refers to the entire match- Non-capturing groups:
\%(pattern\)— groups without creating a capture - Capture groups work in all Vim regex contexts