Regex in Python
Python's regular expressions live in the standard-library module re. Its syntax is very close to JavaScript's, so everything you learned with the tester carries over — with a few differences in naming and defaults that this lesson highlights.
Raw strings
Always write patterns as raw strings — r"\d+". In a normal string, Python itself would process escapes like \b (backspace!) before the regex engine ever sees them:
import re
print(re.findall("\bcat\b", "cat scat")) # \b became a backspace character
print(re.findall(r"\bcat\b", "cat scat")) # raw string: \b is a word boundary[]
['cat']
The functions
| Function | Returns | JavaScript equivalent |
|---|---|---|
re.search(p, s) |
first Match anywhere, or None |
s.match(re) without g |
re.match(p, s) |
Match only at the start, or None |
/^…/ |
re.fullmatch(p, s) |
Match if the whole string matches |
/^…$/ |
re.findall(p, s) |
list of strings (or tuples of groups) | s.match(re_g) |
re.finditer(p, s) |
iterator of Match objects |
s.matchAll(re_g) |
re.sub(p, r, s) |
new string (all matches by default) | s.replace(re_g, r) |
re.subn(p, r, s) |
(new_string, count) |
— |
re.split(p, s) |
list of pieces | s.split(re) |
re.compile(p, flags) |
a reusable Pattern object |
new RegExp(p, flags) |
Note that sub and findall work on all matches — there is no g flag in Python.
import re
s = "Order 66 shipped 2025-04-12; order 7 pending"
print(re.search(r"\d+", s).group())
print(re.match(r"\d+", s))
print(re.fullmatch(r"[\w\s;-]+", s) is not None)
print(re.findall(r"\d+", s))
print(re.split(r";\s*", s))66
None
True
['66', '2025', '04', '12', '7']
['Order 66 shipped 2025-04-12', 'order 7 pending']
Match objects
import re
m = re.search(r"(?P<user>\w+)@(?P<host>[\w.]+)", "mail: quang@hue.edu.vn!")
print(m.group(), m.start(), m.end(), m.span())
print(m.group(1), m["host"])
print(m.groups())
print(m.groupdict())quang@hue.edu.vn 6 22 (6, 22)
quang hue.edu.vn
('quang', 'hue.edu.vn')
{'user': 'quang', 'host': 'hue.edu.vn'}
Because search returns None when nothing matches, check before using the result. The walrus operator makes that tidy:
import re
for line in ["temp=21.5", "humidity high", "temp=-3"]:
if (m := re.fullmatch(r"temp=(-?\d+(?:\.\d+)?)", line)):
print("temperature", float(m[1]))
else:
print("skip:", line)temperature 21.5
skip: humidity high
temperature -3.0
findall and groups
findall changes shape depending on the groups in the pattern: no groups → list of whole matches; one group → list of that group; several → list of tuples.
import re
s = "w=10 h=20"
print(re.findall(r"\w=\d+", s))
print(re.findall(r"\w=(\d+)", s))
print(re.findall(r"(\w)=(\d+)", s))['w=10', 'h=20']
['10', '20']
[('w', '10'), ('h', '20')]
Flags
| Python | Inline | Meaning |
|---|---|---|
re.IGNORECASE / re.I |
(?i) |
case-insensitive |
re.MULTILINE / re.M |
(?m) |
^ $ per line |
re.DOTALL / re.S |
(?s) |
. matches \n |
re.VERBOSE / re.X |
(?x) |
whitespace and comments |
re.ASCII / re.A |
(?a) |
\w, \d, \s, \b ASCII-only |
import re
text = "Name: An\nname: Binh\nNAME: Chi"
print(re.findall(r"^name: (\w+)quot;, text, re.I | re.M))
print(re.findall(r"(?im)^name: (\w+)quot;, text))['An', 'Binh', 'Chi']
['An', 'Binh', 'Chi']
Differences from JavaScript
| Topic | Python re |
JavaScript |
|---|---|---|
\w, \d, \b |
Unicode by default | ASCII only |
| Named group | (?P<n>…), backref (?P=n) |
(?<n>…), backref \k<n> |
| Replacement refs | \1, \g<n> |
$1, lt;n> |
\p{L} |
not supported (use the regex package) |
with u/v |
| Lookbehind | fixed width only | any width |
| End of string | \Z (and $) |
$ only |
| Inline flags | (?i), (?i:…) |
not supported in older engines |
| Atomic groups / possessive | Python 3.11+ | not supported |
Test yourself
Which function requires the whole string to match?
re.searchre.matchre.fullmatchre.findall
What does re.findall(r"(\d)(\w)", "1a 2b") return?
['1a', '2b']['1', '2'][('1', 'a'), ('2', 'b')]None
Why write r"\bword\b" instead of "\bword\b"?
- Raw strings are faster
- In a normal string
\bis a backspace character - Raw strings ignore case
- It's required by
re.compile