7. Quantifiers

A quantifier says how many times the item immediately before it may repeat:

  • * — zero or more times.
  • + — one or more times.
  • ? — zero or one time, to make it optional.
  • {n} — exactly n times.
  • {n,m} — between n and m times, both included.
  • {n,} — n or more times.
  • A quantifier applies to the one item before it: a character, \d, \w, or a group.
  • Matching is greedy: it takes as many characters as possible while still allowing the rest of the pattern to match.
  • ? after another quantifier, such as +?, makes it lazy and stops at the shortest match. That is outside this lesson.
  • * can match zero characters, so a pattern like a* can produce empty strings; use it next to something else, such as ba*.

Coming from JavaScript? the symbols are the same, and both engines are greedy by default.

#01

One or more with +

The + quantifier means one or more of the item before it. Use r"a+" on "aaa b aa c" and print the matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Zero or more with *

The * quantifier means zero or more, so the item may be absent. Use r"ba*" on "ba baa b" and print the matches. The last b matches because it has zero a characters after it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Optional with ?

The ? quantifier means zero or one time, so the item before it is optional. Use r"colou?r" on "color colour" and print the matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Exactly n with {n}

{n} means exactly n repetitions. Use r"a{3}" on "a aa aaa" and print the matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Between n and m with {n,m}

{n,m} means between n and m repetitions, both included. Use r"a{2,3}" on "a aa aaa aaaa" and print the matches. Matching is greedy, so aaaa gives one match of three a characters and leaves the fourth.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

n or more with {n,}

{n,} means n or more repetitions, with no upper limit. Use r"\w{7,}" on "ala casa fantastico" and print the matches. Only words with at least seven word characters match.

Print exactly:

Create a free account to save your progress and unlock chapter 2.