liveBook · Manning

Re

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

re is Python's standard-library module for matching and manipulating text with regular expressions.

re is Python’s standard-library module for describing text patterns and matching, replacing, or splitting text. It is useful when ordinary string methods would require manually writing several search-and-replace steps. section 8.6 section 14.1.2

The core operations demonstrated here are:

  • Use re.sub(pattern, replacement, text) to create a modified string while leaving the original unchanged. section 8.3.2 section 8.6
  • Use character classes such as [aeiou] to match one character from a set, and add + to match one or more consecutive characters. section 14.1.2
  • Use re.match() for a pattern beginning at the start of text, re.search() for a match beginning anywhere, and re.split() for pattern-based splitting. section 14.1.2 section 15.1.1

Replace vowels

>>> import re >>> pattern = '[aeiou]' >>> re.sub(pattern, 'o', 'Apples and bananas!') 'Applos ond bononos!' For both cases, apply two substitutions when preserving capitalization: >>> text = 'Apples and Bananas!' >>> re.sub('[AEIOU]', 'O', re.sub('[aeiou]', 'o', text)) 'Opplos ond Bononos!' section 8.3.2

Match initial consonants

Build a character class from the lowercase consonants, then match one or more at the beginning of a word: >>> consonants = 'bcdfghjklmnpqrstvwxyz' >>> re.match(f'[{consonants}]+', 'chair') <re.Match object; span=(0, 2), match='ch'> >>> re.match(f'[{consonants}]+', 'apple') >>> type(re.match(f'[{consonants}]+', 'apple')) <class 'NoneType'> section 14.1.2

>>> vowel = 'o'
>>> re.sub(pattern, vowel, 'Apples and bananas!')
'Applos ond bononos!'

Run a minimal re.sub example and inspect the returned replacement string. section 8.3.2

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

How deep it goes
Introduces character classes, repetition, matching position, substitution, and splitting, but deliberately scratches only the surface of regexes.
Examples
Demonstrates vowel replacement, initial-consonant matching, and comma-based splitting.
What it assumes
Assumes Python strings and basic iteration while teaching regular-expression character classes and repetition from concrete examples.
What you can do after
Apply it via Python’s re module to replace matched text, detect patterns at chosen positions, and split text with regex delimiters.
How it connects
Connects regular expressions with string replacement, string splitting, character classes, and list comprehensions used to construct patterns.

Also explained in

Compare how 2 books explain re →

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.