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}— exactlyntimes.{n,m}— betweennandmtimes, both included.{n,}—nor 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 likea*can produce empty strings; use it next to something else, such asba*.
Coming from JavaScript? the symbols are the same, and both engines are greedy by default.
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.
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.
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.
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.
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.
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.