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

Quantifiers on Groups

~8 min · groups, quantifier, capture

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

The quantifier applies to the whole group

You've seen this in earlier lessons. (ab)+ matches one or more repetitions of 'ab'. (\d{3})? matches an optional 3-digit group. The group is just a way to make the quantifier scope multiple characters.

The capture surprise

Here's the gotcha: when a capturing group has a quantifier, the captured value is only the LAST iteration. Not the full repeated match — just the final round.

Pattern (ab)+ against ababab: the full match is ababab, but group 1's captured value is ab (just the last iteration). To capture the full repeated string, wrap the entire repetition: ((ab)+) — outer group 1 captures ababab, inner group 2 captures the last ab.

Use non-capturing for grouping-only

If you don't need to capture the group's value, use a non-capturing group (?:...). It groups for the quantifier but doesn't allocate a capture slot. Tracks 4 covers this in detail.

For now, the pattern (?:ab)+ repeats 'ab' without trying to capture anything — cleaner and slightly faster.

Code

Quantifiers on groups·python
import re

# Whole group repeats
re.findall(r'(ab)+', 'abababab abc')
# ['ab', 'ab']  — the GROUP captures last iteration only

# To get the full match including all iterations, use re.finditer
for m in re.finditer(r'(ab)+', 'abababab'):
    print(m.group(0), m.group(1))
# 'abababab' 'ab'  — group(0) is full match; group(1) is last iteration

# Capture the whole repeated chunk: outer group
m = re.match(r'((ab)+)', 'abababab')
print(m.group(1))  # 'abababab'  — outer captures everything
print(m.group(2))  # 'ab'        — inner is still last iteration

# Non-capturing — cleanest when you only need the grouping
re.findall(r'(?:ab)+', 'abababab')
# ['abababab']  — no capture, full match returned

External links

Exercise

Write a pattern that captures all repeated 3-letter blocks in a string like 'fooBARbazFOO'. Predict whether (\w{3})+ will return one block or all three. Run it. Then fix it to actually return all three using re.findall(r'\w{3}', ...) instead — sometimes the right answer isn't a quantifier at all.

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.