PYTHON ADVANCEDChapter 9 · Python Advanced
Regular expressions
A regular expression is a pattern for matching text. The re module searches with it: re.findall(pattern, text) returns every match, re.search finds the first one, and re.sub replaces matches. Common pieces: \d is a digit, \w a word character, + means one or more, * zero or more, [aeiou] any one of these letters, and ( ) captures part of a match. Write patterns as raw strings, r"...", so backslashes stay as typed.
Worked example
How it reads
\d+means one or more digits in a row- The parentheses in
(\d+)capture a part you can read withgroup(1) re.subreplaces every match with new text
Common mistakes
- Forgetting the
rprefix: in a normal string,"\b"is a backspace character, not a word boundary.

Cloud tip: Regex is powerful but easy to misread. For simple jobs like splitting on commas, plain string methods are clearer.


