liveBook · Manning

Greedy matching

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

A regular-expression matching behavior in which a quantifier selects the longest possible substring that still permits the pattern to match.

Greedy matching makes a regular-expression quantifier such as * or + consume as many characters as possible while still allowing the pattern to match. With <.+>, the dot spans multiple placeholders and stops at the final >, not the first. section 17.1.1

Matching angle-bracket placeholders

Given `The quick <adjective> <noun> jumps ...`, `re.search('(<.+>)', text)` returns the entire span from `<adjective>` through the final `>`. Use `<.+?>` to stop at `<adjective>`, or `<[^<>]+>` to exclude both angle brackets from the contents and preserve balanced pairs. section 17.1.1

Control the match when a greedy quantifier crosses the intended delimiter:

  • Append `?` to make `+` or `*` non-greedy, selecting the shortest possible match. section 17.1.1
  • Prefer a negated character class such as `[^<>]+` when the contents must not contain either delimiter. section 17.1.1

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

How deep it goes
Explains greedy, non-greedy, and delimiter-excluding patterns with interactive examples, but does not cover regex-engine internals.
Examples
Demonstrates `<.+>`, `<.+?>`, and `<[^<>]+>` against placeholder text and unbalanced brackets.
What it assumes
Assumes basic regular-expression syntax and Python interaction while teaching greedy behavior from a concrete parsing task.
What you can do after
Diagnose/debug with Python regular expressions by identifying overmatching and choosing non-greedy or delimiter-excluding patterns.
How it connects
Connects greedy matching with regular expressions, quantifiers, non-greedy matching, character classes, and delimiter matching.

Also explained in

Compare how 2 books explain greedy matching →

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.