liveBook · Manning

Optional quantifier

As explained in The Quick Python Book, Fourth Edition

An optional quantifier allows the preceding regular-expression element to occur zero or one time.

In a regular expression, ? makes the element immediately before it optional: that element may occur zero or one time. Group the element first when several characters belong together. section 16.4

Use the optional quantifier to accommodate small format variations:

  • Add (\d{3}-)? to allow a phone number to include an area code or omit it. section 16.4
  • Add ( [-a-zA-Z]+)? to allow a record to include a middle name or initial. section 16.4
  • Use {3} when expressing a fixed three-digit repetition inside an optional group. section 16.4

Optional area code

The pattern (\d{3}-)?\d{3}-\d{4} matches both 555-123-4567 and 123-555-123-4567. The question mark applies to the entire grouped area-code sequence. section 16.4

(\d\d\d-)?\d\d\d-\d\d\d\d

Compare a required phone-number prefix with the same prefix made optional by grouping it and adding ?. section 16.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines zero-or-one matching and demonstrates grouping, repetition counts, and combined name-and-phone patterns.
Examples
Uses phone numbers with optional area codes and names with optional middle names or initials.
What you can do after
Apply via Python’s re module to match records whose area codes or middle names may be missing.
How it connects
Connects optional quantifiers with regular expressions, grouping, repetition counts, and named groups.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.