Parentheses scope a piece of pattern
You've already seen parentheses doing scope work in earlier tracks. (ab)+ repeats 'ab' three times; (abc|def) matches either 'abc' or 'def'. The parentheses don't change what's matched — they just tell the engine "this is one thing."
Four jobs in one syntax
Parentheses do four distinct things, all packed into the same syntax:
- Scope a quantifier or alternation —
(ab)+,(abc|def) - Capture a value —
(\d{4})-(\d{2})captures year and month into groups 1 and 2 - Apply lookaround / atomic / etc. — special group syntax like
(?=...),(?:...),(?>...) - Provide a target for backreferences —
(\w+) \1matches "word, then the same word again"
This is why parentheses are such workhorses — and why "do I need a capturing group here, or just grouping?" is one of the most common decisions you'll make.
Default is capturing
Plain (...) is a CAPTURING group. The matched substring is allocated a slot you can reference later (group 1, group 2, etc.). If you only need the grouping for scoping (no backreference, no extraction), use the explicitly non-capturing (?:...) covered in lesson 4.