Describe Classes and Quantifiers
Core idea
A character class such as [A-Z] matches one character from a range. Quantifiers apply to the preceding atom: ? means zero or one, * zero or more, + one or more, and {m,n} from m to n repetitions. Ordinary quantifiers are greedy, preferring more repetitions subject to a match.
import rep = r"[A-Z]{2}-[0-9]{3}"print(bool(re.fullmatch(p,"AB-123")))print(bool(re.fullmatch(p,"A-1234")))The pattern requires exactly two ASCII capitals, a hyphen, and three ASCII digits.
Compare greedy and lazy repetitions
import res = "<a><b>"print(re.search(r"<.*>",s).group())print(re.search(r"<.*?>",s).group())Appending ? to * makes it lazy, preferring fewer repetitions; this simple example is not an HTML parser.
Common mistake
Use [0-9] for an ASCII-only requirement rather than assuming \d is ASCII. Use fullmatch when validating a label.
Practice
Validate a label with two capitals, a hyphen and three ASCII digits.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Classes and quantifiers
Check your understanding of character classes and quantifiers.
What is printed?
import reprint(bool(re.fullmatch(r"[0-9]{2}","09")), bool(re.fullmatch(r"[0-9]{2}","9")))What is printed?
import reprint(re.search("a+","aaab").group())Which quantifier requires at least one occurrence?
What does [A-Z] match?