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

Range: {n,} and {n,m}

~6 min · quantifier, range, bounded

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

From n to m occurrences

The {} braces support three forms:

  • {n} — exactly n (lesson 4)
  • {n,} — n or more, no upper bound
  • {n,m} — between n and m, inclusive

Pattern \d{3,4} matches 3 OR 4 digits. Pattern a{2,} matches 2 or more a's. Pattern x{0,5} matches 0 to 5 x's (similar to x* but capped at 5).

Equivalences worth knowing

The basic quantifiers are shortcuts for {} ranges:

  • * is {0,}
  • + is {1,}
  • ? is {0,1}

You'll never write {0,} in real code — * is shorter. But knowing the equivalence makes the family feel coherent.

The flavor wart: comma whitespace

Most engines require NO whitespace inside {}. {3, 5} with a space is interpreted differently across flavors — sometimes as a literal, sometimes as an error, almost never as {3,5}. Always write {n,m} tight.

Code

Range quantifiers·python
import re

# 3 or 4 digits — phone area code or year
re.findall(r'\b\d{3,4}\b', 'call 415 then 2026 then 90210')
# ['415', '2026']  — 90210 is 5 digits, not matched

# 2 or more — runs of duplicate letters
re.findall(r'(\w)\1{2,}', 'AAAA bbb cccc ddddd')
# ['A', 'b', 'c', 'd']

# Cap with upper bound — at most 8 hex digits
re.findall(r'\b[0-9a-fA-F]{1,8}\b', '0xFF 0xDEADBEEF 0x123456789')
# ['0xFF', '0xDEADBEEF']  — last is 9 hex digits, exceeds cap

# Equivalences
import re
re.match(r'a{1,}', 'aaa').group() == re.match(r'a+', 'aaa').group()  # True

External links

Exercise

Write a username validator: 3-20 characters, letters+digits+underscore, must start with a letter. Test 'a' (too short), 'thisis_aLong_username' (OK), 'this_is_way_too_long_for_us' (too long), '1starts_wrong'.

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.