Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 05

Quantifiers — How Many Characters a Pattern Needs

Count each Python regex match with +, *, ?, and braces such as {m} and {m,n} for an exact count or a minimum and maximum.

Intermediate25 min
Quantifiers hero Module 18 Lesson 5 plus star question braces

A quantifier sits after a character or a class and says how many times that piece may repeat.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • +, *, ?, and {m} / {m,n}
  • Why * and ? can match an empty piece
  • How quantifiers combine with \d and \w
  • Why a literal dot must be escaped

The picture

The same letter, different counts

Put the quantifier immediately after the thing you want to count.

Pattern How many
a exactly one a
a+ one or more
a* zero or more
a? zero or one
a{m} exactly m
a{m,n} at least m and at most n
. any one character except a newline

+ is the one you will use most. * and ? are allowed to succeed on nothing, so findall with them can return empty strings between other characters. Prefer search when you only want to see whether an optional piece is there.

The same marks work on classes:

Pattern Meaning
\d+ one or more digits
\d{10} exactly 10 digits
\d{m} exactly m digits
\d{m,n} from m to n digits
\w+ one or more word characters
[A-Za-z]{3} exactly three letters

A dot in a pattern means "any character." A decimal point in a number must be written \. so it is a real dot. \d{2}\.\d{2} is two digits, a dot, and two digits.

Example

python
import re

text = "aaa ba aaaa"
print(re.findall(r"a+", text))
print(re.findall(r"a{2}", text))
print(re.search(r"a?", "b").group() == "")
print(re.findall(r"\d{2}\.\d{2}", "score 18.50 and 7"))

a+ returns aaa, the single a inside ba, and aaaa. a{2} takes the letters two at a time and does not keep a leftover single a. The third line is true because a? may match nothing. The last line keeps 18.50 and skips 7.

Key takeaways

  • + is one or more; * is zero or more; ? is zero or one

  • {m} is an exact count; {m,n} is a range

  • A class can wear a quantifier: \d+, \d{10}, [A-Za-z]{3}

  • Escape a real dot as \.

  • Next: Validation Patterns — a code, a word, and a decimal

  • Previous: Predefined Classes

Loading playground…

Check your understanding

Quantifiers quiz

a+ matches:

1 / 10