liveBook · Manning

Regular expression

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

A regular expression is a pattern notation for matching and extracting text according to specified character and sequence rules.

A regular expression is a declarative pattern for finding, extracting, validating, splitting, or replacing text. Instead of manually inspecting characters, describe the pattern and let Python’s regex engine search the input. section 14.0 section 14.5

Build patterns from a small set of useful operations:

  • Use character classes such as [aeiou], [A-Za-z0-9], or [^<>] to describe allowed or excluded characters. section 14.1.2 section 18.1.1
  • Use re.match() for a match at the beginning, re.search() for a match anywhere, re.split() to divide text, and re.compile() for repeated use. section 14.1.2 section 15.5
  • Add quantifiers such as + for one or more characters, and anchors such as $ for the end of a string. section 14.1.2 section 15.1.5
  • Wrap parts in parentheses to capture them, then retrieve the captured text with match.group() or match.groups(). section 14.3.2 section 17.1.1
  • Remember that * and + are greedy; adding ? makes them non-greedy, while a negated class can express a precise boundary. section 17.1.1 section 17.5

Match initial consonants

Construct a consonant character class, then anchor it to the beginning with re.match(). The + quantifier captures a whole initial cluster, so “chair” produces “ch,” while “apple” produces no match. import re consonants = 'bcdfghjklmnpqrstvwxyz' match = re.match(f'[{consonants}]+', 'chair') print(match.group()) # ch The same pattern supports a rhyming-word program by separating leading consonants from the rest of a word. section 14.1.2

Extract placeholders without overmatching

A greedy pattern such as <.+> consumes from the first opening bracket to the last closing bracket. Use <[^<>]+> instead to stop at a balanced pair and exclude nested brackets. Capture the complete placeholder and its name separately: match = re.search('(<([^<>]+)>)', '<adjective>') print(match.groups()) # ('<adjective>', 'adjective') re.findall() returns every placeholder, allowing a program to prompt for each name before re.sub() replaces the matches. section 17.1.1 section 17.5

>>> re.split("([a-zA-Z](?:[a-zA-Z']*[a-zA-Z])?)", "Don't worry, spiders,")
['', "Don't", ' ', 'worry', ', ', 'spiders', ',']

Inspect a runnable split pattern that preserves words containing apostrophes while separating surrounding punctuation and whitespace. section 16.1.1

Long patterns remain maintainable when adjacent string literals are split across lines and comments document each part. Small functions and tests make regex-based transformations easier to verify and reuse. section 14.3.2 section 14.5

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

How deep it goes
Descends from character classes and quantifiers to captures, greediness, substitution, and compiled patterns, while leaving advanced regex usage unexplored.
Examples
Uses rhyming words, word scrambling, Mad Libs placeholders, ASCII-word cleaning, workout ranges, and Tic-Tac-Toe boards.
What you can do after
Apply it via Python’s re module to find, capture, validate, split, clean, and replace structured text.
How it connects
Connects character classes, capture groups, greedy matching, string substitution, input validation, list comprehensions, and testing.

Also explained in

Compare how 27 books explain regular expression →

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.