Python Standard Library · Lesson 121 of 149

Python Regular Expressions

What you will learn

  • What a regular expression is and when to use one
  • The re functions: search, match, fullmatch, findall, finditer, sub, split
  • Pattern syntax: characters, classes, quantifiers, anchors, groups
  • Named groups, greedy versus lazy, lookarounds
  • Flags and re.compile
  • Common mistakes and limits

1. Patterns for text

A regular expression (regex) is a short code that describes a pattern of text: "three digits, a dash, four digits". The re module searches, extracts and replaces text that matches a pattern. String methods (lesson 4.4) are enough for fixed text ("cat" in text); use regex when the text varies in a describable way: phone numbers, dates, emails, codes in a log.

Always write patterns as raw strings, r"...", so that backslashes reach the regex engine unchanged (lesson 4.1): r"\d" rather than "\\d".

import re

text = "Call Rina on 017-1234-5678 or Sam at 018-9999-0000."

2. The main functions

print(re.search(r"\d{3}-\d{4}-\d{4}", text))
print(re.search(r"\d{3}-\d{4}-\d{4}", text).group())
print(re.search(r"zzz", text))
<re.Match object; span=(13, 26), match='017-1234-5678'>
017-1234-5678
None
Function What it does Returns
re.search(p, s) finds the first match anywhere a match object, or None
re.match(p, s) matches only at the start match or None
re.fullmatch(p, s) the whole string must match match or None
re.findall(p, s) all matches a list of strings
re.finditer(p, s) all matches, lazily match objects
re.sub(p, repl, s) replaces matches a new string
re.split(p, s) splits at matches a list

A match object knows details:

m = re.search(r"(\d{3})-(\d{4})-(\d{4})", text)
print(m.group(0), m.group(1), m.groups())
print(m.start(), m.end(), m.span())
017-1234-5678 017 ('017', '1234', '5678')
13 26 (13, 26)

group(0) is the whole match; group(1), group(2) ... are the parts in parentheses. Always check for None before using a match, or you get an AttributeError:

re.search(r"\d+", "abc").group()
AttributeError: 'NoneType' object has no attribute 'group'

A safe style is if m := re.search(...): (lesson 5.6).

match versus search versus fullmatch:

print(re.match(r"Call", text) is not None, re.match(r"Rina", text))
print(re.fullmatch(r"\d+", "123") is not None, re.fullmatch(r"\d+", "123a"))
True None
True None

Use fullmatch to validate a whole value.

Quick check: which function tells you whether an entire string is made of digits: `search`, `match` or `fullmatch`?

fullmatch(r"\d+", s). The others succeed if only part of the string matches.

3. Pattern syntax

Characters and classes

Pattern Matches
abc the literal text abc
. any one character except a newline
\d / \D a digit / a non-digit
\w / \W a "word" character (letter, digit, _) / not
\s / \S whitespace / not
[aeiou] any one of the listed characters
[a-z0-9] a range
[^aeiou] any character not listed
\. \+ \( a literal special character (escape it)
a\|b a or b
print(re.findall(r"[aeiou]", "education"))
print(re.findall(r"[^aeiou\s]+", "hello world"))
['e', 'u', 'a', 'i', 'o']
['h', 'll', 'w', 'rld']

Quantifiers (how many)

Pattern Meaning
x? zero or one
x* zero or more
x+ one or more
x{3} exactly 3
x{2,4} 2 to 4
x{2,} 2 or more
print(re.search(r"colou?r", "color") is not None)
print(re.findall(r"\d+(?:\.\d+)?", "3.14 and 42 and 0.5"))
True
['3.14', '42', '0.5']

(?:...) groups without capturing.

Anchors and boundaries

Pattern Meaning
^ / $ start / end of the string (of each line with re.M)
\b a word boundary
print(re.findall(r"\bcat\b", "cat concat cat."))
print(re.findall(r"cat", "cat concat"))
['cat', 'cat']
['cat', 'cat']

The first uses boundaries, so it matches the two whole words cat and not the one inside concat. The second has no boundaries, so it finds cat in cat and in concat. Both lists have two items, but they are not the same two places.

4. Groups

Parentheses make groups: they capture the parts so you can read them, and findall returns the groups when there are any:

print(re.findall(r"(\d{3})-(\d{4})", text))
[('017', '1234'), ('018', '9999')]

Named groups (?P<name>...) make the code readable:

m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", "Date: 2026-03-05.")
print(m["year"], m.group("month"))
print(m.groupdict())
2026 03
{'year': '2026', 'month': '03', 'day': '05'}

\1 refers back to the first group inside the pattern, which finds repetition:

print(re.search(r"(\w+) \1", "this is is a test").group())
print(re.sub(r"\b(\w+)( \1\b)+", r"\1", "the the cat cat sat"))
is is
the cat sat

5. Replacing and splitting

print(re.sub(r"\d", "#", "a1b22"))
print(re.sub(r"\s+", " ", "a   b \n c"))
print(re.sub(r"(\w+)@(\w+)", r"\2 at \1", "rina@example"))
print(re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "3 apples and 10 pears"))
print(re.split(r"[,;]\s*", "a, b;c,d"))
a#b##
a b c
example at rina
6 apples and 20 pears
['a', 'b', 'c', 'd']
  • In the replacement text, \1, \2 insert groups.
  • Give sub a function to compute the replacement from each match.
  • re.split splits on a pattern: spaces, commas or semicolons in any mix.

6. Greedy or lazy?

Quantifiers are greedy: they take as much as they can. Add ? to make them lazy:

print(re.findall(r"<.+>", "<a><b>"))
print(re.findall(r"<.+?>", "<a><b>"))
['<a><b>']
['<a>', '<b>']

The greedy .+ ran to the last >; the lazy .+? stopped at the first one. This is the most common surprise for beginners.

7. Lookarounds

A lookaround checks what is next to the position without including it in the match:

Pattern Meaning
(?=...) followed by
(?!...) not followed by
(?<=...) preceded by
(?<!...) not preceded by
print(re.findall(r"(?<=\$)\d+", "cost $50 and $7"))
print(re.findall(r"\d+(?= USD)", "5 USD 6 EUR"))
print(re.sub(r"(?<=\d)(?=(\d{3})+$)", ",", "1234567"))
['50', '7']
['5']
1,234,567

The last one inserts commas as thousands separators (lesson 4.6 shows an easier way: f"{n:,}").

8. Flags and compile

Flags change the matching rules:

Flag Short Effect
re.IGNORECASE re.I ignore case
re.MULTILINE re.M ^ and $ match at each line
re.DOTALL re.S . also matches a newline
re.VERBOSE re.X allow spaces and comments in the pattern
re.ASCII re.A \d, \w only match ASCII
print(re.findall(r"a.c", "abc a\nc"))
print(re.findall(r"a.c", "abc a\nc", re.DOTALL))
print(re.findall(r"^\w+", "one\ntwo", re.M))
print(re.findall("hello", "Hello HELLO", re.I))
print(re.findall(r"\d", "٣4"), re.findall(r"\d", "٣4", re.ASCII))
['abc']
['abc', 'a\nc']
['one', 'two']
['Hello', 'HELLO']
['٣', '4'] ['4']

The last line shows that \d matches digits of other scripts (here an Arabic-Indic three) unless you use re.ASCII.

re.compile builds a pattern object once, to reuse (and to name it):

pat = re.compile(r"\d+")
print(pat.findall("a1b22"), pat.sub("N", "a1b22"))
print(pat.pattern, type(pat).__name__)
print([m.group() for m in re.finditer(r"\d+", "a1b22c333")])
['1', '22'] aNbN
\d+ Pattern
['1', '22', '333']

A bad pattern raises re.error:

re.compile("(")
re.PatternError: missing ), unterminated subpattern at position 0

Use re.escape(text) to match user-supplied text literally: re.escape("a.b*c") returns a\.b\*c.

9. Limits

  • Regexes are hard to read. Prefer simple patterns, re.VERBOSE with comments, and named groups. Test them on examples.
  • Do not parse HTML or other nested formats with regex; use a parser (html.parser, json, csv).
  • Email and URL validation is full of exceptions. A simple pattern checks the rough shape, but the only real test is to send a message.
  • A pattern copied from the internet should be tested on your data; some patterns can take forever on unlucky input ("catastrophic backtracking"), a security risk with untrusted text.

Worked example: extracting data from a text

Pull emails, phone numbers and dates out of a block of text, read each contact card into a dictionary, mask a phone number, and validate user names.

import re

text = """Contacts:
Rina Khan <rina@example.com>, phone 017-1234-5678
Sam Lee <sam.lee@mail.org>, phone 018-9999-0000
Bad entry: lee@, phone 12-34
Meeting on 2026-03-05 and 2026-04-12."""

email = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
phone = re.compile(r"\b\d{3}-\d{4}-\d{4}\b")
date = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})")

print(email.findall(text))
print(phone.findall(text))
for m in date.finditer(text):
    print(m.group(), "->", f"{m['day']}/{m['month']}/{m['year']}")

card = re.compile(
    r"^(?P<name>[A-Z][a-z]+ [A-Z][a-z]+) <(?P<mail>[^>]+)>, phone (?P<tel>[\d-]+)$",
    re.M)
for m in card.finditer(text):
    print(m.groupdict())

print(re.sub(r"(\d{3})-(\d{4})-(\d{4})", r"\1-****-\3", text.splitlines()[1]))
print(re.sub(r"\d{4}-\d{2}-\d{2}", lambda m: m.group()[:4], "from 2026-03-05 to 2027-01-01"))


def valid_username(name):
    return re.fullmatch(r"[a-z][a-z0-9_]{2,15}", name) is not None


print([valid_username(n) for n in ["rina_k", "9lives", "ab", "ok_name_1", "UPPER"]])
['rina@example.com', 'sam.lee@mail.org']
['017-1234-5678', '018-9999-0000']
2026-03-05 -> 05/03/2026
2026-04-12 -> 12/04/2026
{'name': 'Rina Khan', 'mail': 'rina@example.com', 'tel': '017-1234-5678'}
{'name': 'Sam Lee', 'mail': 'sam.lee@mail.org', 'tel': '018-9999-0000'}
Rina Khan <rina@example.com>, phone 017-****-5678
from 2026 to 2027
[True, False, False, True, False]
Piece Idea
[\w.+-]+@[\w-]+(?:\.[\w-]+)+ a rough email shape; the bad entry lee@, is not matched
\b\d{3}-\d{4}-\d{4}\b whole phone numbers only; 12-34 is skipped
named groups on dates readable reordering with an f-string
re.M with ^ and $ the card pattern is applied to each line
sub with a function keeps only the year
fullmatch a username must match entirely: 3 to 16 characters, starting with a lower-case letter

The names, emails and numbers are made up. Compare the earlier simple email pattern \w+@\w+\.\w+, which found k@mail.org instead of sam.k@mail.org: it cut off at the dot in the name.

Common mistakes

  • Forgetting the raw string ("\d" instead of r"\d").
  • Using the result without checking for None.
  • Using match or search to validate (use fullmatch).
  • Greedy .+ swallowing too much.
  • Forgetting to escape ., +, (, ? when you mean the literal character.
  • Expecting findall to return whole matches when the pattern has groups.
  • Building one huge unreadable pattern.
  • Parsing HTML with regex.

Key takeaways

  • Write patterns as raw strings and use the re functions: search, fullmatch, findall, finditer, sub, split.
  • Core syntax: classes (\d, \w, [a-z]), quantifiers (?, *, +, {n,m}), anchors (^, $, \b), groups ((...), (?P<name>...)).
  • Quantifiers are greedy; add ? for lazy; lookarounds check context without consuming it.
  • Always check a match for None; use fullmatch for validation.
  • Use re.compile, flags and verbose patterns to keep regexes readable; use real parsers for structured formats.

Practice

1. Write a pattern that matches a time like 09:45.

Show answer

r"\d{2}:\d{2}" (for a stricter check of hours and minutes, r"([01]\d|2[0-3]):[0-5]\d").

2. What is the difference between re.search and re.fullmatch?

Show answer

search finds a match anywhere in the string; fullmatch requires the pattern to match the entire string.

3. Why does re.findall(r"<.+>", "<a><b>") return one item?

Show answer

.+ is greedy and runs to the last >. Use the lazy <.+?> to get <a> and <b> separately.

4. Replace all runs of whitespace in s with a single space.

Show answer

re.sub(r"\s+", " ", s)

5. How do you read the day from a match made with the named group (?P<day>\d{2})?

Show answer

m["day"] or m.group("day").

6. Why should you check if m: before m.group()?

Show answer

When nothing matches, search returns None, and None.group() raises AttributeError.