Regular Expressions in Python
Describe a text pattern once, then search, extract, validate, and replace with it
re module reads that pattern and finds every place in a string that matches.
- read a pattern made of literals, metacharacters, character classes, and quantifiers;
- use the core
refunctions —search,findall,sub,split, andcompile; - capture pieces of a match with groups and named groups;
- solve everyday tasks: validating, extracting, and cleaning text;
- recognise when a regex is the wrong tool and reach for something simpler instead.
1. What is a regular expression?
Think of a regex as a stencil for text. A stencil is a card with a shape cut out of it; lay it over a page and only the parts that fit the hole show through. A regex is the same idea for strings: you describe a shape once, and the engine slides it across the text reporting every place the shape fits.
You have already searched text the blunt way with "needle" in haystack or str.find. Those only match an exact run of characters. A regex matches a family of strings: \d{4} matches any four digits — 1999, 2026, 0000 — without you listing them. That single idea is what makes regex powerful for phone numbers, dates, log lines, and file names.
In Python you reach this power through the standard-library module re. Nothing to install — just import re.
2. The re module: your toolbox
Five functions cover almost everything you will do. Each takes the pattern first and the text second.
| Function | What it does | Returns |
|---|---|---|
re.search(p, s) | Find the first place the pattern matches anywhere in s | a Match object, or None |
re.findall(p, s) | Find all non-overlapping matches | a list of strings |
re.sub(p, r, s) | Replace every match with r | a new string |
re.split(p, s) | Split s everywhere the pattern matches | a list of pieces |
re.compile(p) | Pre-build a pattern to reuse it many times | a Pattern object |
A first taste — pull the first "word@word.word" token out of a sentence:
import re
text = "Contact ada@example.com for details."
m = re.search(r"\w+@\w+\.\w+", text)
print(m.group())
Output:
ada@example.com
r"\d+", not "\d+". The r stops Python from treating the backslash as an escape before re ever sees it. Without it "\b" becomes a backspace character and your pattern silently breaks.