liveBook · Manning

Re.findall()

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

re.findall() is a Python regular-expression function that returns all non-overlapping matches of a pattern in a string.

re.findall() returns every non-overlapping match for a regular-expression pattern. With capture groups, it returns matching groups as tuples in parenthesis order. section 17.1.1 section 17.5

A practical extraction pattern:

  • Use `re.findall('(<([^<>]+)>)', text)` to find angle-bracketed placeholders while capturing both the complete placeholder and its inner name. section 17.1.1
  • Iterate with `for placeholder, name in matches:` to unpack each two-tuple and build prompts or other processing steps. section 17.1.1

Extracting Mad Libs placeholders

For `The quick <adjective> <noun> jumps <preposition> the lazy <noun>.`, the call returns `[('<adjective>', 'adjective'), ('<noun>', 'noun'), ('<preposition>', 'preposition'), ('<noun>', 'noun')]`. section 17.1.1

>>> from pprint import pprint
>>> matches = re.findall('(<([^<>]+)>)', text)
>>> pprint(matches)
[('<adjective>', 'adjective'),
('<noun>', 'noun'),
('<preposition>', 'preposition'),
('<noun>', 'noun')]

Inspect the complete interactive output showing every extracted placeholder and its captured name. section 17.1.1

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

How deep it goes
Explains list and tuple results, capture-group ordering, and tuple unpacking, but defers broader regular-expression implementation details.
Examples
Demonstrates extracting adjective, noun, and preposition placeholders from a fox-themed Mad Libs sentence.
What you can do after
Apply it via Python's re module to extract repeated pattern matches and process captured values.
How it connects
Connects regular expressions, capture groups, greedy matching, non-greedy matching, and re.sub().

Also explained in

Compare how 2 books explain re.findall() →

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.