A quantifier is a regular-expression construct that controls how many times the preceding element may or must occur. It handles variable-length patterns such as h, hi, hhi, and hhhi, while simpler startswith or endswith calls remain preferable when they are sufficient. section 2.4.3
Choose a quantifier according to the allowed number of occurrences:
- ? allows zero or one occurrence; * allows zero or more; + requires one or more. section 2.4.3
- {3} requires exactly three occurrences; {1,3} allows one through three; {2,} requires two or more. section 2.4.3
- The forms ?, *, and + are greedy by default; adding another ? makes the match shortest rather than longest. section 2.4.3
Compare quantifier behavior
import re test_string = "h hi hii hiii hiiii" patterns = [r"hi?", r"hi*", r"hi+", r"hi{2,3}", r"hi+?"] for pattern in patterns: print(pattern, re.findall(pattern, test_string)) # hi? ['h', 'hi', 'hi', 'hi', 'hi'] # hi* ['h', 'hi', 'hii', 'hiii', 'hiiii'] # hi+ ['hi', 'hii', 'hiii', 'hiiii'] # hi{2,3} ['hii', 'hiii', 'hiii'] # hi+? ['hi', 'hi', 'hi', 'hi'] For text extraction, use quantifiers when separators or other pattern elements occur a variable number of times; for example, data values separated by one or more separators require a quantified pattern. section 2.4.7


