liveBook · Manning

Re.match

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

re.match() is a Python re-module function that attempts to match a regular expression at the beginning of a string and returns a match object or None.

re.match() tests a regular expression at the beginning of a string. It returns a re.Match object when the pattern matches and None otherwise; unlike re.search(), it does not begin searching later in the text. section 14.1.2 section 14.1.3

Split a word at its first vowel

>>> pattern = f'([{consonants}]+)?([aeiou])(.*)' >>> re.match(pattern, 'chair').groups() ('ch', 'a', 'ir') >>> re.match(pattern, 'apple').groups() (None, 'a', 'pple') >>> type(re.match(pattern, 'rdnzl')) <class 'NoneType'> Parentheses create capture groups, ? makes the leading consonants optional, and re.IGNORECASE handles uppercase input. section 14.1.3 section 14.1.3

>>> text = 'chair'
>>> re.match(pattern, text)                 #1
<re.Match object; span=(0, 1), match='c'>   #2

Inspect a successful beginning-of-string match on “chair.” section 14.1.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains return values, capture groups, quantifiers, optional patterns, and case flags, while stopping short of regex-engine internals.
Examples
Demonstrates consonant matching in “chair,” vowel splitting in “cake,” “chair,” and “apple,” and failures for “rdnzl” and “123.”
What it assumes
Assumes familiarity with Python strings and functions while building character classes, list comprehensions, and regular-expression patterns incrementally.
What you can do after
Apply Python’s re module to test prefixes, inspect match objects, retrieve groups, and handle unsuccessful matches.
How it connects
Connects regular expressions with re.search(), re.Match, capture groups, character classes, quantifiers, and re.IGNORECASE.

Also explained in

Compare how 2 books explain re.match →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.