C.W.K.
Stream
Lesson 01 of 12 · published

Grouping with Parentheses

~6 min · groups, parentheses, scope

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

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:

  1. Scope a quantifier or alternation(ab)+, (abc|def)
  2. Capture a value(\d{4})-(\d{2}) captures year and month into groups 1 and 2
  3. Apply lookaround / atomic / etc. — special group syntax like (?=...), (?:...), (?>...)
  4. Provide a target for backreferences(\w+) \1 matches "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.

Code

Parentheses doing different jobs·python
import re

# Scoping a quantifier — repeat 'ab' three or more times
re.findall(r'(ab){3,}', 'ababab abababab abc')
# ['ab', 'ab']  — captures last iteration of group

# Scoping an alternation — match 'cat' or 'dog'
re.findall(r'(cat|dog)s?', 'cats and dogs and cat-dog')
# ['cat', 'dog', 'cat', 'dog']

# Capturing a value
m = re.match(r'(\d{4})-(\d{2})', '2026-05-04')
m.group(1), m.group(2)
# ('2026', '05')

# Backreference target
bool(re.search(r'(\w+) \1', 'the the cat sat'))
# True  — 'the' followed by 'the'

External links

Exercise

Take a pattern with three parens. Decide for each: is it capturing (you use the value), or scoping-only (it's just there for the quantifier/alternation)? Convert the scoping-only ones to (?:...). The pattern should behave identically and read more clearly.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.