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

Exact Count: {n}

~5 min · quantifier, exact

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

Repeat exactly n times

{n} means "exactly n occurrences of the previous element." Not more, not less.

Pattern \d{4} matches exactly four digits. Pattern a{3} matches exactly three a's. Pattern (ab){5} matches exactly five repetitions of 'ab' (so 'ababababab').

Where it shines

Fixed-length data formats: 4-digit years, 16-digit credit card numbers, 6-character hex colors, 5-digit ZIP codes, 4-block UUIDs. Anywhere the spec says "exactly N characters," {n} says it back.

Watch the boundary

By itself, \d{4} happily matches 4 consecutive digits in the middle of a longer run. re.findall(r'\d{4}', '20260504') returns ['2026', '0504'] — both 4-digit chunks of the 8-digit string. To prevent this, anchor with \b or ^...$: \b\d{4}\b won't match if there are digits on either side.

Code

{n} for fixed-length·python
import re

# Exactly 4 digits
re.findall(r'\d{4}', 'year 2026 zip 90210 long 12345678')
# ['2026', '9021', '1234', '5678']  — surprises in the long ones

# Anchored with word boundaries — only standalone 4-digit numbers
re.findall(r'\b\d{4}\b', 'year 2026 zip 90210 long 12345678')
# ['2026']

# Hex color (6 hex digits after #)
re.findall(r'#[0-9a-fA-F]{6}\b', 'use #FF8FBE or #abcdef as the brand')
# ['#FF8FBE', '#abcdef']

# Group repeated exactly
re.findall(r'(ab){3}', 'ababab abababab ababXX')
# ['ab', 'ab']  — captures the LAST repetition; we'll fix this in groups track

External links

Exercise

Write the smallest pattern that matches a US ZIP code (exactly 5 digits) but NOT the 9-digit ZIP+4 form. Then a second pattern that matches BOTH forms. Test both against 90210, 90210-1234, 9021012345.

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.