Python RegEx
A regular expression (regex) is a small pattern language for describing text: "three digits, a dash, then four digits", "a word that starts with a capital letter". Python's built-in re module uses these patterns to search, extract, validate and replace text.
Tip: Always write patterns as raw strings —
r"\d+"— so that backslashes reach the regex engine untouched.
The main functions
| Function | Does |
|---|---|
re.search(p, s) |
finds the first match anywhere, returns a match object or None |
re.match(p, s) |
matches only at the start of the string |
re.fullmatch(p, s) |
the whole string must match |
re.findall(p, s) |
list of all matches |
re.finditer(p, s) |
iterator of match objects |
re.sub(p, repl, s) |
replace matches |
re.split(p, s) |
split the string at matches |
import re
text = "Order 66 shipped on 2025-04-12, order 7 is pending."
m = re.search(r"\d+", text)
print(m.group(), m.start(), m.end())
print(re.findall(r"\d+", text))
print(re.match(r"\d+", text)) # text doesn't START with digits
print(re.split(r"[,.]\s*", text))66 6 8
['66', '2025', '04', '12', '7']
None
['Order 66 shipped on 2025-04-12', 'order 7 is pending', '']
Pattern building blocks
| Pattern | Matches |
|---|---|
. |
any character except newline |
\d / \D |
a digit / a non-digit |
\w / \W |
a word character (letter, digit, _) / anything else |
\s / \S |
whitespace / non-whitespace |
[abc] |
one of a, b, c |
[a-z0-9] |
a range of characters |
[^abc] |
any character except a, b, c |
^ / $ |
start / end of the string |
\b |
a word boundary |
a|b |
a or b |
\. |
a literal dot (escape special characters) |
Quantifiers
| Quantifier | Means |
|---|---|
* |
0 or more |
+ |
1 or more |
? |
0 or 1 (optional) |
{3} |
exactly 3 |
{2,4} |
2 to 4 |
import re
words = "cat cart coat ct caaat"
print(re.findall(r"\bca*t\b", words)) # c, any number of a's, t
print(re.findall(r"\bc\w+t\b", words))
print(re.findall(r"colou?r", "color colour colouur"))
print(re.findall(r"\b\w{4}\b", "this line has many four word sets"))['cat', 'ct', 'caaat']
['cat', 'cart', 'coat', 'caaat']
['color', 'colour']
['this', 'line', 'many', 'four', 'word', 'sets']
Groups: extracting parts
Parentheses create groups, which capture pieces of the match. Named groups (?P<name>...) make the code self-explanatory:
import re
log = "2025-04-12 08:15:02 ERROR disk full"
m = re.match(r"(\d{4})-(\d{2})-(\d{2}) (\S+) (\w+) (.*)", log)
print(m.group(1), m.group(2), m.group(3))
print(m.groups()[3:])
pattern = r"(?P<user>[\w.]+)@(?P<domain>[\w.]+\.\w+)"
for m in re.finditer(pattern, "Mail an.nguyen@example.com or info@shop.vn"):
print(m.group("user"), "at", m.group("domain"))2025 04 12
('08:15:02', 'ERROR', 'disk full')
an.nguyen at example.com
info at shop.vn
When a pattern contains groups, findall returns the groups instead of the whole match:
import re
prices = "apple $1.20, melon $3.75, grapes $12.00"
print(re.findall(r"(\w+) \$(\d+\.\d\d)", prices))[('apple', '1.20'), ('melon', '3.75'), ('grapes', '12.00')]
Replacing with re.sub
The replacement can refer back to groups as \1, \2, or be a function:
import re
print(re.sub(r"\s+", " ", "too many spaces"))
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "Due 2025-04-12"))
print(re.sub(r"\d", "#", "Card 4111 2222", count=4))
print(re.sub(r"\b\w", lambda m: m.group().upper(), "hello big world"))too many spaces
Due 12/04/2025
Card #### 2222
Hello Big World
Flags and compiled patterns
Flags change how a pattern behaves. If you use a pattern many times, compile it once with re.compile:
import re
print(re.findall(r"python", "Python PYTHON python", flags=re.IGNORECASE))
phone = re.compile(r"^0\d{9}quot;)
for number in ["0912345678", "912345678", "09123x5678"]:
status = "valid" if phone.fullmatch(number) else "invalid"
print(number, status)['Python', 'PYTHON', 'python']
0912345678 valid
912345678 invalid
09123x5678 invalid
| Flag | Effect |
|---|---|
re.IGNORECASE / re.I |
case-insensitive matching |
re.MULTILINE / re.M |
^ and $ match at every line |
re.DOTALL / re.S |
. also matches newlines |
re.VERBOSE / re.X |
allow whitespace and comments in the pattern |
Note:
*and+are greedy — they match as much as possible. Add?(*?,+?) for the shortest match:re.findall(r"<.+?>", "<b>hi</b>")gives['<b>', '</b>'].
Test yourself
What does re.findall(r"\d+", "a1b22c333") return?
- ['1', '2', '2', '3', '3', '3']
- ['1', '22', '333']
- ['a', 'b', 'c']
- '122333'
What does re.search return when there is no match?
- An empty string
- False
- None
- It raises an error
Why should regex patterns be written as raw strings like r"\d"?
- They run faster
- So Python doesn't interpret backslashes as escape sequences
- Raw strings are required by the re module
- To make them case-insensitive