re (regular expressions)
The re module finds, extracts and replaces text that follows a pattern, instead of a fixed piece of text.
Used in 28 lessons of the course, from 00.06.
re is a standard library module for working with regular expressions: patterns that describe what a piece of text looks like.
First you write import re. Then you pass a pattern and a string to a function such as re.search, re.findall or re.sub.
The pattern almost always goes in a raw string (r"\d+"). The r stops Python from interpreting the backslash before re sees it. So \d arrives intact and means "one digit".
re.search returns a Match object if it finds something, or None if not. That is why you usually check if m: before using it.
The course uses it from lesson 00.06 with import re, to clean and pull parts out of text, for example a model's reply.
re.findall(r"\d+", "a1b22") # ['1', '22']
Reach for it when: the text you want isn't fixed but follows a shape, like numbers, dates or quoted words.
Examples
Common mistake
import re m = re.search(r"\d+", "no digits here") print(m.group())
Why: When nothing matches, `search` returns `None`, and `None` has no `group` method.
How to write it: Check first: if m: print(m.group()).
Common mistake
import re print(re.match(r"\d+", "abc 123"))
Why: `re.match` only looks at the start of the string, so it misses the 123 further along.
How to write it: Use re.search to look anywhere in the text.
