Quantifiers let one pattern match inputs of different lengths, such as numbers, words and optional parts.
A quantifier follows an item (a character, a class or a group) and says how many times it may repeat:
*zero or more:ab*cmatchesac,abc,abbbc.+one or more:\d+matches a whole run of digits.?zero or one, i.e. optional:colou?rmatchescolorandcolour.{3}exactly three,{2,4}two to four,{2,}two or more.
A quantifier applies only to the single item right before it. ab+ means a followed by one or more bs; to repeat a sequence, group it: (ab)+ matches ababab.
By default quantifiers are greedy: they take as much as possible while still letting the overall pattern match. That is usually what you want for runs of digits or letters, and it is the source of the classic .* surprises covered in the greedy versus lazy lesson.
Be careful with patterns that can match the empty string, like \d*. They "succeed" at positions where nothing interesting is present, so re.findall(r"\d*", "a1") returns empty matches as well as '1'. Prefer + when you need at least one character.
Example
import re
print(re.findall(r"ab*c", "ac abc abbbc")) # ['ac', 'abc', 'abbbc']
print(re.findall(r"\d+", "order 66 of 1977")) # ['66', '1977']
print(re.findall(r"colou?r", "color colour")) # ['color', 'colour']
print(re.findall(r"\b\d{4}\b", "in 1977, 42, 12345")) # ['1977']
print(re.findall(r"(?:ab)+", "abababx ab")) # ['ababab', 'ab']
print(re.findall(r"\d*", "a1")) # ['', '1', ''] empty matches!
print(re.findall(r"\d+", "a1")) # ['1']Remember
- * zero or more, + one or more, ? optional, {m,n} bounded
- A quantifier applies to the one item before it; group to repeat a sequence
- Quantifiers are greedy by default
Watch out for
- Using * where + was meant, so the pattern also matches the empty string.