liveBook · Manning

Quantifier

As explained in Python How-To

A quantifier is a regular-expression construct that specifies how many occurrences of a preceding element may or must appear.

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

How Python How-To covers it

How deep it goes
Defines six quantifier forms, demonstrates greedy and non-greedy matching, and stops short of regular-expression engine internals.
Examples
Demonstrates h and i repetitions, Python re.findall output, and extraction from values separated by one or more separators.
What it assumes
Assumes basic Python string handling and regular-expression patterns while introducing quantifier selection for variable-length matches.
What you can do after
Apply it via Python regular expressions to match bounded, unbounded, greedy, or shortest variable-length sequences.
How it connects
Connects quantifiers with regular expressions, character classes, anchors, pattern groups, string searching, and text extraction.

Also explained in

Compare how 3 books explain quantifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.