Skip to content

Regular expressions

A regular expression (regex) is a small pattern language for text: find, validate, extract, split and replace. This page covers Python’s re syntax and functions, with examples on the course log file data/logs/app.log, and the pandas .str methods that take the same patterns.

I want to… Use… Example
test if a pattern occurs anywhere re.search(p, s) if re.search(r"\bERROR\b", line):
test if a pattern starts the string re.match(p, s) re.match(r"\d{4}-\d{2}-\d{2}", line)
validate a whole value re.fullmatch(p, s) re.fullmatch(r"P\d{3}", pid)
get every match as strings re.findall(p, s) re.findall(r"\d+ms", text)
get every match with positions and groups re.finditer(p, s) for m in re.finditer(p, text):
replace matches re.sub(p, repl, s) re.sub(r"\s+", " ", s)
replace with computed text re.sub(p, func, s) re.sub(r"\d+", lambda m: str(int(m[0]) * 2), s)
count replacements re.subn(p, repl, s) new, n = re.subn(...)
split on a pattern re.split(p, s) re.split(r"[;,]\s*", "a, b;c")
reuse a pattern re.compile(p, flags) LINE = re.compile(r"...")
match a literal string safely re.escape(s) re.search(re.escape("1.5 (x)"), s)
capture a part (...) and m[1] re.search(r"(\d+)ms", line)[1]
capture with a name (?P<name>...) and m["name"] m["status"]
group without capturing (?:...) (?:GET|POST) /\S+
one of several words \b(?:a|b|c)\b \b(?:WARNING|ERROR)\b
match the shortest text a lazy quantifier *?, +? <.+?>
require text after, without taking it lookahead (?=...) \d+(?=ms)
forbid text after negative lookahead (?!...) \buser=(?!-)\S+
require text before lookbehind (?<=...) (?<=user=)\S+
ignore case re.IGNORECASE or (?i) re.search(r"error", s, re.I)
^ and $ at every line re.MULTILINE re.findall(r"^\S+", text, re.M)
. across newlines re.DOTALL re.search(r"Traceback.*?Error", text, re.S)
a readable, commented pattern re.VERBOSE spaces and # comments inside the pattern
a dict of named groups m.groupdict() {"method": "GET", ...}
swap parts in a replacement \1, \g<name> re.sub(r"(\d+)/(\d+)", r"\2/\1", s)
extract columns in pandas s.str.extract(p) named groups become column names
filter rows in pandas s.str.contains(p) df[df["line"].str.contains(r"\bERROR\b")]

Write every pattern as a raw string r"...". In a normal string, Python handles backslashes before re sees them: "\b" is a backspace character, and "\d" is an invalid escape that triggers a SyntaxWarning.

import re
print(len("\b"), len(r"\b")) # 1 character vs 2 characters
print(re.findall(r"\bms\b", "87ms 93 ms"), re.findall("\bms\b", "87ms 93 ms"))
print(re.escape("price (USD) 1.5")) # escape text you want to match literally
Output
1 2
['ms'] []
price\ \(USD\)\ 1\.5
Pattern Matches Example → match
a, 7, - that literal character r"GET" → GET
. any character except \n (with re.S, also \n) r"a.c" → abc, a-c
\d / \D a digit / a non-digit (Unicode digits too) r"\d\d" → 87
\w / \W a word character [a-zA-Z0-9_] plus Unicode letters / other r"\w+" → user_42
\s / \S whitespace (space, tab, newline) / other r"\S+" → one token
[abc] one of the listed characters r"[aeiou]"
[a-z0-9] a range r"[A-F0-9]+" → hex
[^abc] any character not listed r"[^,]+" → one CSV field
[.], [$], [*] most special characters are literal inside [] r"[.]" → .
\., \*, \(, \[, \\ an escaped literal r"1\.5" → 1.5
\t, \n tab, newline
\b / \B a word boundary / not a boundary (zero width) r"\bINFO\b"
Greedy Lazy Possessive (3.11+) Repeats
* *? *+ 0 or more
+ +? ++ 1 or more
? ?? ?+ 0 or 1
{n} exactly n
{m,n} {m,n}? {m,n}+ m to n
{m,} {m,}? {m,}+ m or more

Greedy takes as much as it can, then backs off. Lazy takes as little as it can. Possessive takes as much as it can and never backs off (faster failures, fewer matches).

import re
html = "<b>Wireless</b> <i>Earbuds</i>"
print(re.findall(r"<.+>", html)) # greedy: one match spans everything
print(re.findall(r"<.+?>", html)) # lazy: each tag
print(re.findall(r"<[^>]+>", html)) # a negated class: often the clearest
print(re.findall(r"\d{2,3}", "7 87 1188"), re.findall(r"\d{2,3}?", "1188"))
Output
['<b>Wireless</b> <i>Earbuds</i>']
['<b>', '</b>', '<i>', '</i>']
['<b>', '</b>', '<i>', '</i>']
['87', '118'] ['11', '88']
Pattern Matches at Note
^ the start of the string with re.M: the start of every line
$ the end of the string, or before a final \n with re.M: the end of every line
\A the start of the string only ignores re.M
\Z the end of the string only ignores re.M
\b a word boundary between \w and \W
Pattern Meaning
(...) capturing group; numbered from 1 by its opening parenthesis
(?P<name>...) named group; read with m["name"]
(?:...) group without a capture (for | or a quantifier)
a|b a or b; the leftmost alternative that matches wins
\1, (?P=name) the same text again, inside the pattern
\1, \g<1>, \g<name> a group’s text in a sub replacement
(?>...) atomic group (3.11+): never backtracks into it
(?(1)yes|no) conditional: yes if group 1 matched
Pattern Means Example → match
X(?=Y) X followed by Y r"\d+(?=ms)" on 93ms → 93
X(?!Y) X not followed by Y r"\b\d+\b(?!ms)"
(?<=Y)X X preceded by Y r"(?<=user=)\S+" → the user
(?<!Y)X X not preceded by Y r"(?<!-)\b\d+" → positive numbers

A lookbehind must have a fixed width in Python’s re: (?<=user=) works, (?<=\w+=) raises re.error.

import re
line = "17:18:02,430 ERROR [api] 198.51.100.23 POST /api/v1/predict 500 1188ms"
print(re.findall(r"\d+(?=ms)", line)) # the number before "ms", without "ms"
print(re.search(r"(?<=\[)\w+(?=\])", line)[0]) # the text inside [ ]
pw = re.compile(r"(?=.*\d)(?=.*[A-Z]).{8,}") # several conditions at once
print([bool(pw.fullmatch(p)) for p in ["secret12", "Secret12", "Sh0rt"]])
Output
['1188']
api
[False, True, False]
Flag Inline Effect
re.IGNORECASE, re.I (?i) case-insensitive
re.MULTILINE, re.M (?m) ^ and $ at each line
re.DOTALL, re.S (?s) . also matches \n
re.VERBOSE, re.X (?x) whitespace ignored, # starts a comment
re.ASCII, re.A (?a) \w, \d, \s, \b match ASCII only
combine (?im) re.I | re.M
scoped (?i:...), (?-i:...) turn a flag on or off for that group only

Pass flags with a keyword: re.sub(p, repl, s, flags=re.I). The fourth positional argument of re.sub is count, not flags. Python 3.13 deprecates passing count and flags by position.

Function Returns Use for
re.search(p, s) the first Match anywhere, or None “does it contain…?”
re.match(p, s) a Match at position 0, or None prefixes
re.fullmatch(p, s) a Match of the whole string, or None validation
re.findall(p, s) a list of strings; with 1 group its text; with 2+ groups tuples quick extraction
re.finditer(p, s) an iterator of Match objects positions, named groups, large texts
re.sub(p, repl, s, count=0, flags=0) the new string cleaning, masking
re.subn(p, repl, s) (new_string, number_of_replacements) reporting changes
re.split(p, s, maxsplit=0) a list of pieces; captured groups are kept tokenizing
re.compile(p, flags) a Pattern with the same methods reuse; pos and endpos arguments
re.escape(s) s with special characters escaped user input inside a pattern
Match member Gives
m[0], m.group() the whole match
m[1], m["name"], m.group(1, 2) one group, or a tuple of groups
m.groups() all groups as a tuple (None where a group did not take part)
m.groupdict() named groups as a dict
m.start(), m.end(), m.span(g) positions in the string
m.expand(r"\2-\1") a template filled with the groups
bool(m) always True; test if m: or if m is None:
import re
text = "a=1, b=22; c=333"
print(re.findall(r"\d+", text)) # no group: whole matches
print(re.findall(r"(\w)=(\d+)", text)) # 2 groups: tuples
print(re.split(r"[,;]\s*", text), re.split(r"([,;])\s*", text)) # groups kept
print(re.sub(r"(\w)=(\d+)", r"\2=\1", text)) # backreferences
print(re.subn(r"\d", "#", text))
print(re.sub(r"\d+", lambda m: str(int(m[0]) * 2), text)) # computed replacement
m = re.fullmatch(r"(?P<key>\w)=(?P<value>\d+)", "b=22")
print(m.groupdict(), m.span("value"), re.match(r"\d", text))
Output
['1', '22', '333']
[('a', '1'), ('b', '22'), ('c', '333')]
['a=1', 'b=22', 'c=333'] ['a=1', ',', 'b=22', ';', 'c=333']
1=a, 22=b; 333=c
('a=#, b=##; c=###', 6)
a=2, b=44; c=666
{'key': 'b', 'value': '22'} (2, 4) None

The log lines look like this:

data/logs/app.log (excerpt)
2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 200 87ms user=priya.nair@example.com
2024-05-01 08:25:14,977 WARNING [validator] 23 rows with missing customer_id in sales_raw.csv
2024-05-01 10:53:56,110 ERROR [loader] Failed to parse data/reports/2024-04.csv
Traceback (most recent call last):

Parse request lines with a verbose pattern

Section titled “Parse request lines with a verbose pattern”
import re
from collections import Counter
from pathlib import Path
text = Path("data/logs/app.log").read_text(encoding="utf-8")
API = re.compile(
r"""
^(?P<date>\d{4}-\d{2}-\d{2})\s(?P<time>[\d:]{8}),\d{3}\s
(?P<level>[A-Z]+)\s\[api\]\s
(?P<ip>\d{1,3}(?:\.\d{1,3}){3})\s
(?P<method>GET|POST|PUT|DELETE)\s(?P<path>\S+)\s
(?P<status>\d{3})\s(?P<ms>\d+)ms\s
user=(?P<user>\S+)$
""",
re.VERBOSE | re.MULTILINE, # spaces ignored; ^ and $ per line
)
requests = [m.groupdict() for m in API.finditer(text)]
print(len(requests), requests[0]["method"], requests[0]["path"], requests[0]["ms"])
print(Counter(r["status"] for r in requests).most_common(3))
slow = [r for r in requests if int(r["ms"]) >= 1000]
print(len(slow), sorted({r["path"] for r in slow}))
Output
391 GET /api/v1/reports/2024-04 87
[('200', 250), ('201', 77), ('429', 13)]
2 ['/api/v1/predict', '/api/v1/products?page=2']
levels = Counter(re.findall(r"^\S+ \S+ (DEBUG|INFO|WARNING|ERROR)\b", text, re.M))
print(sorted(levels.items()))
errors = re.findall(r"^.* ERROR \[(\w+)\] (.*)$", text, re.MULTILINE)
print(len(errors), errors[0])
line = text.splitlines()[0]
print(re.sub(r"(?<=user=)[^@\s]+@", "***@", line).split()[-1]) # keep the domain
users = set(re.findall(r"user=([\w.+-]+@[\w-]+\.\w+)", text))
print(len(users), sorted(users)[:2])
Output
[('DEBUG', 13), ('ERROR', 7), ('INFO', 447), ('WARNING', 25)]
7 ('db', 'OperationalError: database is locked (attempt 1/3), retrying in 1s')
user=***@example.com
8 ['ana.silva@example.com', 'diego.ramos@example.net']
tb = re.compile(r"^Traceback.*?^(\w+Error): ([^\n]*)", re.MULTILINE | re.DOTALL)
for m in tb.finditer(text): # lazy .*? stops at the first error line
# with DOTALL, a greedy (.*) here would run to the end of the file
print(m[1], "|", m[2][:45])
Output
ValueError | Usecols do not match columns, columns expecte
ValueError | Usecols do not match columns, columns expecte

pandas string methods take the same patterns. They work on a whole column at once. The full .str reference is on the pandas page.

Method Regex by default? Returns
s.str.contains(p, case=True, regex=True) yes a boolean Series (for filtering)
s.str.match(p) / s.str.fullmatch(p) yes boolean: anchored at the start / whole value
s.str.extract(p) yes a DataFrame: one column per group; named groups name the columns
s.str.extractall(p) yes one row per match (a MultiIndex with match)
s.str.findall(p) yes a list of matches per row
s.str.count(p) yes the number of matches per row
s.str.replace(p, repl, regex=True) no: pass regex=True new strings; repl may be a function
s.str.split(p, regex=True, expand=True) only for patterns longer than 1 character lists or columns
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
lines = pd.Series(text.splitlines(), dtype="str")
api = lines[lines.str.contains(r"\[api\]")]
pattern = r"(?P<method>GET|POST) (?P<path>\S+) (?P<status>\d{3}) (?P<ms>\d+)ms"
parts = api.str.extract(pattern) # named groups -> column names
parts["ms"] = parts["ms"].astype(int)
print(parts.groupby("method")["ms"].median())
print(api.str.replace(r"user=\S+", "user=***", regex=True).iloc[0][-40:])
Output
method
GET 32.0
POST 88.0
Name: ms, dtype: float64
api/v1/reports/2024-04 200 87ms user=***
Data Pattern Note
ISO date \d{4}-\d{2}-\d{2} format only; validate with date.fromisoformat
time 08:04:01 \d{2}:\d{2}:\d{2}
integer, optional sign [-+]?\d+
decimal number [-+]?\d+(?:\.\d+)? add (?:[eE][-+]?\d+)? for 1e3
money such as $1,299.00 \$(\d{1,3}(?:,\d{3})*\.\d{2}) remove commas before float()
an id such as O000123 \bO\d{6}\b \b stops partial matches
simple email [\w.+-]+@[\w-]+(?:\.[\w-]+)+ real validation: send a mail
IPv4 address \b\d{1,3}(?:\.\d{1,3}){3}\b use ipaddress.ip_address() to validate
URL path and query (/[^\s?]*)(?:\?(\S*))? use urllib.parse.urlsplit for full URLs
key=value pairs (\w+)=(\S+) dict(re.findall(...))
quoted string "([^"\\]*(?:\\.[^"\\]*)*)" handles \" inside
repeated whitespace \s+ → " " " ".join(s.split()) is simpler
a word from a list \b(?:INFO|WARNING|ERROR)\b build with "|".join(map(re.escape, words))
blank lines ^\s*$ with re.M
Trap Symptom Fix
a pattern without r"..." \b never matches; SyntaxWarning: invalid escape sequence always use raw strings
re.match for “contains” None although the text is there re.search; fullmatch for validation
re.search for validation "P0011" passes P\d{3} re.fullmatch, or anchor with \A...\Z (not $, which accepts a trailing newline)
findall with groups returns group text or tuples, not the whole match (?:...) for non-capturing groups, or finditer
greedy .* one match swallows several fields or tags .*?, or a negated class [^,]*
. and newlines a multi-line block does not match re.DOTALL
^ and $ match only once in a multi-line text re.MULTILINE
re.sub(p, r, s, re.I) the flag is taken as count flags=re.I
a None match TypeError: 'NoneType' object is not subscriptable test if m: before m[1]
user input in a pattern re.error or wrong matches on . ( + re.escape(user_text)
a backslash in a sub replacement re.error: bad escape double it, or use a function as repl
\d matches Unicode digits "٣" passes \d re.ASCII or [0-9]
variable-width lookbehind re.error: look-behind requires fixed-width pattern capture a group instead
nested quantifiers such as (a+)+ catastrophic backtracking: the program hangs simplify; atomic groups or possessive quantifiers
regex for HTML, JSON or CSV breaks on nesting and quoting html.parser/BeautifulSoup, json, csv
pandas str.replace the pattern is treated as plain text pass regex=True
pandas str.contains with (, . or ? in plain text wrong matches or a warning about groups regex=False for literal text