When should I use a capturing group or a non-capturing group in a regex?
Quick answer
Use a capturing group, (…), when you need its matched text as a result or to refer to it later. Use a non-capturing group, (?:…), when parentheses are only grouping pattern parts. For example, capture the word and number in item-42 but use a non-capturing group for the hyphen if you do not need it in the results. Captures are numbered in opening-parenthesis order, so adding one can shift later group numbers.
The question, the details, the next step.
A practical checklist
List the exact substrings your code needs after matching.
Use
(…)for text you want to capture and(?:…)for grouping alone.Number capturing groups in opening-parenthesis order; non-capturing groups add no capture.
After changing a pattern, recheck numeric references and result positions.
Try a representative input and inspect the captured values.
A few more useful answers
Does a non-capturing group still affect whether the pattern matches?
Yes. It groups parts of the pattern without adding a captured value. In the example, (?:-) still requires the hyphen.
If I add a capturing group, do later group numbers stay the same?
Not necessarily. Adding a capture can shift the numbers of later captures, so review code that refers to them by number.
Do these examples apply to every regex engine?
No. The syntax and behavior described here are for Python’s standard re module and JavaScript regular expressions. Check the documentation for another engine or API.
Sources
References used for this guide.
- [S1] Python 3.15 re — Regular expression operations docs.python.org · Checked
- [S2] MDN JavaScript Guide: Groups and backreferences developer.mozilla.org · Checked
