TExcelTAD
Home › Regular Expressions › Regex in Python

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:

python · try it yourself
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.

python · try it yourself
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

python · try it yourself
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:

python · try it yourself
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.

python · try it yourself
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
python · try it yourself
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?

  1. re.search
  2. re.match
  3. re.fullmatch
  4. re.findall

What does re.findall(r"(\d)(\w)", "1a 2b") return?

  1. ['1a', '2b']
  2. ['1', '2']
  3. [('1', 'a'), ('2', 'b')]
  4. None

Why write r"\bword\b" instead of "\bword\b"?

  1. Raw strings are faster
  2. In a normal string \b is a backspace character
  3. Raw strings ignore case
  4. It's required by re.compile