Group without allocating a capture slot
(?:...) behaves like (...) for grouping purposes — quantifiers and alternation work the same — but does NOT capture the matched text into a numbered group. The match exists; it just doesn't get a slot.
Why bother
Three reasons to prefer non-capturing when you don't need the value:
- Clarity. The reader sees
(?:...)and immediately knows "this is grouping, not extraction." Capturing groups raise the question "what's this for?" - Group numbering stability. If you add or remove a non-capturing group, the numbers of capturing groups elsewhere don't shift. With pure
(...), every change to the pattern can renumber every reference downstream. - Slight performance. No capture slot to allocate. Tiny gain, but free.
The 'I'll capture everything just in case' anti-pattern
Beginners often capture every group reflexively, then never use most of the captures. The result: noisy code, brittle group numbers, slightly slower matching. Capture only what you'll actually use; non-capture everything else.