How do I group part of a Vim regex pattern without creating a numbered capture group?
Answer
\%(...\)
Explanation
Vim's standard grouping syntax \(...\) creates a capture group numbered \1, \2, etc. When you need grouping for alternation or quantifiers but don't want to occupy a capture slot, use \%(...\) — a non-capturing group.
How it works
\(...\)— captures the match; accessible as\1in the replacement\%(...\)— groups without capturing; does not increment the\1counter
This matters when you have complex patterns that mix grouping for quantifiers with groups you actually want to reference in the replacement.
Example
Match lines starting with either error: or warn:, capturing what follows:
/\%( error:\|warn:\)\s*\(.*\)/
Here the outer \%(...\) groups the alternation without capturing it, so \1 refers only to the content after the prefix — exactly what you want for use in a substitution or for back-references.
Compare with the capturing equivalent, where \1 would be error: or warn: and \2 would be the message:
/\( error:\|warn:\)\s*\(.*\)/
Tips
- Use
\%(...\)any time you need grouping purely for structure (alternation\|, quantifiers\+,\*,\?) - Keeps capture numbering predictable in complex patterns — you always know which
\Ncorresponds to which meaningful group - Works the same in all pattern contexts:
/,:s,:g,:vimgrep