Python Regular Expressions: A Practical Guide to the `re` Module

0
Python Regular Expressions: A Practical Guide to the `re` Module

Regular expressions describe patterns in text. Python’s built-in re module can locate values in logs, validate simple formats, extract structured fields, split records, and transform text without external packages.

The two skills to learn separately are:

  1. Writing a pattern that describes the intended text.
  2. Selecting the operation that applies the pattern correctly.

A correct pattern passed to the wrong function can still produce an incorrect result. In particular, finding a valid substring is not the same as validating an entire input.

This guide was updated for Python 3.15. Unless marked otherwise, its examples also work with Python 3.10 and later. Possessive quantifiers and atomic groups require Python 3.11; \z requires Python 3.14; prefixmatch() requires Python 3.15.

Your first regular expression

Suppose a log message contains an order number:

import re

message = "Order #48217 was shipped"
match = re.search(r"\d+", message)

if match is not None:
    print(match.group())  # 48217

The pattern \d+ contains two elements:

  • \d matches a Unicode decimal digit in a normal str pattern.
  • + requires one or more repetitions of the preceding element.

re.search() scans from left to right and returns the first matching Match object. It returns None when no match exists.

A Match object provides both the matched text and its location:

import re

match = re.search(r"\d+", "Order #48217 was shipped")
assert match is not None

assert match.group() == "48217"
assert match.start() == 7
assert match.end() == 12
assert match.span() == (7, 12)

As with a Python slice, the ending offset is exclusive.

Why patterns usually use raw strings

Regular expressions and Python string literals both assign meaning to backslashes. Raw string notation prevents Python’s string parser from processing most backslash sequences before the regex engine receives them:

digit_pattern = r"\d+"
word_boundary = r"\bPython\b"

Without raw notation, a sequence such as "\b" becomes a backspace character before re sees it. Since Python 3.12, unrecognized escapes in ordinary string literals produce a SyntaxWarning and may become errors in a future version.

Raw strings still have limitations. A raw string cannot end with an odd number of backslashes because the final backslash would escape its closing quote:

valid = r"\\"

The raw prefix only controls Python’s parsing. It does not disable regular expression syntax: \d still means a decimal digit to the regex engine.

Essential pattern syntax

Most practical patterns use a relatively small set of constructs.

Syntax Meaning
. Any character except a newline, unless re.DOTALL is active
\d Unicode decimal digit
\D Character that is not a Unicode decimal digit
\w Unicode alphanumeric character or underscore
\W Character that is not matched by \w
\s Unicode whitespace
\S Non-whitespace character
[abc] One character from the set
[^abc] One character not in the set
[a-z] One character in the specified range
A|B Alternative: match A or B
(...) Capturing group
(?:...) Non-capturing group
^ Start of the string, or a line with re.MULTILINE
$ End of the string, or immediately before a final newline
\A Start of the string
\z Absolute end of the string in Python 3.14 and later
\b Boundary between word and non-word characters

Metacharacters can be escaped when they should be treated literally. For example, \. matches a period and \| matches a vertical bar.

Inside a character class, most punctuation loses its special meaning. For example, [.+] matches either a literal period or a plus sign.

Quantifiers

Quantifiers specify how often the preceding element may occur.

Quantifier Meaning
* Zero or more
+ One or more
? Zero or one
{3} Exactly three
{2,5} Between two and five
{2,} At least two

An ASCII identifier containing 3–20 characters and beginning with a letter can be expressed as follows:

import re

IDENTIFIER = re.compile(r"[A-Za-z][A-Za-z0-9_]{2,19}")

assert IDENTIFIER.fullmatch("user_42") is not None
assert IDENTIFIER.fullmatch("42_user") is None
assert IDENTIFIER.fullmatch("ab") is None

fullmatch() is important here: the complete input must satisfy the format.

Choose the correct matching operation

The main re operations differ in where they look and what they return.

Operation Behavior Typical use
search() Finds the first match anywhere Locate a value
prefixmatch() Matches only at the beginning Recognize a prefix on Python 3.15+
match() Older name for prefixmatch() Prefix matching on older Python versions
fullmatch() Requires the entire input to match Validate a complete format
findall() Returns all non-overlapping matches as a list Extract values
finditer() Iterates over non-overlapping Match objects Extract values and positions
sub() Replaces matches Transform text
subn() Replaces matches and reports the replacement count Transform and audit
split() Splits at matching separators Tokenize text
import re

text = "ID: 12345"

assert re.search(r"\d+", text).group() == "12345"
assert re.match(r"\d+", text) is None
assert re.fullmatch(r"\d+", text) is None
assert re.fullmatch(r"\d+", "12345") is not None

Python 3.15 added re.prefixmatch() and Pattern.prefixmatch() as clearer names for the behavior historically provided by match(). Python 3.15 soft-deprecates the older name, but the Python project does not plan to remove it. Libraries supporting Python 3.14 and earlier should continue using match() when prefix matching is actually required.

For validation, prefer fullmatch() over adding ^ and $. In particular, $ can match immediately before a final newline, whereas fullmatch() requires the pattern to consume the selected input region.

Extract every match

findall() is convenient when only the matched values matter:

import re

text = "Invoices: 103, 204, and 305"
numbers = re.findall(r"\d+", text)

assert numbers == ["103", "204", "305"]

Use finditer() when positions or other Match methods are needed:

import re

text = "A12 B345"

results = [
    (match.group(), match.span())
    for match in re.finditer(r"\d+", text)
]

assert results == [
    ("12", (1, 3)),
    ("345", (5, 8)),
]

Both functions return non-overlapping matches. Patterns that can match an empty string require extra care because empty matches are included.

Capturing and named groups

Parentheses capture a portion of the match. Named groups make extracted fields easier to understand and less fragile than numeric indexes:

import re

LOG_LINE = re.compile(
    r"(?P<date>\d{4}-\d{2}-\d{2})\s+"
    r"(?P<level>INFO|WARNING|ERROR)\s+"
    r"(?P<message>.+)"
)

line = "2026-11-17 ERROR Payment failed"
match = LOG_LINE.fullmatch(line)
assert match is not None

assert match.group("level") == "ERROR"
assert match.groups() == (
    "2026-11-17",
    "ERROR",
    "Payment failed",
)
assert match.groupdict() == {
    "date": "2026-11-17",
    "level": "ERROR",
    "message": "Payment failed",
}

(?P<name>...) defines a named group. (?:...) groups part of a pattern without capturing it.

Capturing groups change the result returned by findall():

import re

text = "width=20 height=10"

assert re.findall(r"(\w+)=(\d+)", text) == [
    ("width", "20"),
    ("height", "10"),
]

With no capturing groups, findall() returns complete matches. With one capturing group, it returns that group. With multiple groups, it returns tuples. Use non-capturing groups when grouping is needed only for precedence.

Backreferences

A backreference requires text to repeat exactly what an earlier group captured:

import re

text = "This is is a duplicated word."
match = re.search(
    r"\b(?P<word>\w+)\s+(?P=word)\b",
    text,
    re.IGNORECASE,
)

assert match is not None
assert match.group() == "is is"

Numeric backreferences such as \1 are also available, but named references are usually clearer in long patterns.

Greedy, lazy, possessive, and atomic matching

The standard quantifiers are greedy: they consume as much text as possible while still allowing the complete pattern to match. Adding ? makes them lazy, so they initially consume as little as possible.

import re

text = 'name="Ada" role="admin"'

assert re.findall(r'".*"', text) == ['"Ada" role="admin"']
assert re.findall(r'".*?"', text) == ['"Ada"', '"admin"']

Lazy quantifiers still use backtracking. They change which match is preferred, not the regex engine’s fundamental performance model.

Possessive quantifiers and atomic groups

Python 3.11 added possessive quantifiers such as *+, ++, ?+, and {m,n}+. Once a possessive quantifier consumes text, it does not give that text back during backtracking.

import re

assert re.fullmatch(r"a+a", "aaaa") is not None
assert re.fullmatch(r"a++a", "aaaa") is None

The ordinary a+ can surrender one character so the final a can match. The possessive a++ consumes every a and refuses to backtrack.

Atomic groups provide related control:

import re

assert re.fullmatch(r"(?>a+)a", "aaaa") is None

Atomic and possessive constructs can eliminate unnecessary backtracking, but they also change matching behavior. They are targeted tools, not a universal performance switch.

Lookahead and lookbehind

Lookarounds test surrounding text without consuming it.

Syntax Meaning
(?=...) Positive lookahead
(?!...) Negative lookahead
(?<=...) Positive lookbehind
(?<!...) Negative lookbehind

The following pattern extracts a numeric euro amount without including the currency symbol:

import re

text = "The tickets cost €25 and €120."
assert re.findall(r"(?<=€)\d+", text) == ["25", "120"]

A lookahead can require a version number after a product name:

import re

text = "Python 3.15, Python docs, Python 3.11"

matches = re.findall(
    r"\bPython(?=\s+\d)",
    text,
    re.IGNORECASE,
)

assert matches == ["Python", "Python"]

The built-in re engine requires lookbehind patterns to have a fixed width. A lookbehind such as (?<=USD)\d+ is valid because USD always has three characters. (?<=\w+)\d+ is invalid because \w+ can have different lengths.

Flags that change matching behavior

Flags can be supplied to a module-level function or stored in a compiled pattern.

Flag Short name Effect
re.IGNORECASE re.I Enables Unicode-aware case-insensitive matching
re.MULTILINE re.M Lets ^ and $ match at line boundaries
re.DOTALL re.S Lets . match newline characters
re.VERBOSE re.X Allows layout and comments inside a pattern
re.ASCII re.A Gives \w, \d, \s, and related boundaries ASCII semantics
re.DEBUG None Prints the compiled expression’s diagnostic representation

Flags can be combined with the bitwise OR operator:

import re

text = "INFO Started\nERROR Failed\nINFO Retrying"

errors = re.findall(
    r"^error.*$",
    text,
    re.IGNORECASE | re.MULTILINE,
)

assert errors == ["ERROR Failed"]

Write complex patterns with re.VERBOSE

Verbose mode ignores most unescaped whitespace and permits comments outside character classes:

import re

DATE_PATTERN = re.compile(
    r"""
    (?P<year>\d{4})   # Four-digit year
    -
    (?P<month>\d{2})  # Two-digit month
    -
    (?P<day>\d{2})    # Two-digit day
    """,
    re.VERBOSE,
)

assert DATE_PATTERN.fullmatch("2026-11-17") is not None

A literal space in verbose mode must be escaped, placed in a character class, or represented with syntax such as \s.

Unicode and ASCII are different policies

For str patterns, Python uses Unicode semantics by default:

  • \d matches Unicode decimal digits, not only 0 through 9.
  • \w matches Unicode alphanumeric characters plus underscore.
  • \s recognizes Unicode whitespace.
  • \b depends on the definition of \w.

This is often desirable for human text but may be too broad for machine identifiers, protocol fields, or security-sensitive allowlists.

Use explicit ranges or re.ASCII when the format is defined in ASCII:

import re

USERNAME = re.compile(
    r"[a-z][a-z0-9_]{2,19}",
    re.IGNORECASE | re.ASCII,
)

assert USERNAME.fullmatch("Alice_42") is not None
assert USERNAME.fullmatch("álîce") is None

There is another subtlety: [A-Z] with re.IGNORECASE and Unicode matching recognizes the 52 ASCII letters plus four additional characters—İ, ı, Å¿, and K. Combining it with re.ASCII restricts matching to ASCII letters.

Choose the character policy deliberately rather than assuming shorthand classes mean the same thing in every regex engine.

Substitution and splitting

re.sub() replaces non-overlapping matches:

import re

text = "Python   makes\ttext processing easier"
cleaned = re.sub(r"\s+", " ", text)

assert cleaned == "Python makes text processing easier"

A replacement function can calculate each new value:

import re

text = "Tickets: #7, #42, #105"

formatted = re.sub(
    r"#(?P<number>\d+)",
    lambda match: f"#{int(match.group('number')):04d}",
    text,
)

assert formatted == "Tickets: #0007, #0042, #0105"

Replacement strings have their own backreference syntax:

import re

value = "Doe, Jane"
result = re.sub(
    r"(?P<last>\w+),\s*(?P<first>\w+)",
    r"\g<first> \g<last>",
    value,
)

assert result == "Jane Doe"

subn() returns both the transformed string and the number of replacements:

import re

result, count = re.subn(r"\d+", "X", "A1 B22 C333")

assert result == "AX BX CX"
assert count == 3

Use re.split() when separators follow a pattern:

import re

record = "red, green;blue | yellow"
colors = re.split(r"\s*[,;|]\s*", record)

assert colors == ["red", "green", "blue", "yellow"]

Capturing groups in a split pattern cause the captured separators to appear in the result. Use (?:...) when the separator should not be returned.

For a fixed separator or literal replacement, prefer str.split() or str.replace(). They communicate intent more directly.

Validate structure, then validate meaning

A regex can confirm that text has a date-like structure, but it should not duplicate calendar logic. Combine structural matching with the standard library’s domain-specific parser:

import re
from datetime import date

DATE_PATTERN = re.compile(
    r"(?P<year>\d{4})-"
    r"(?P<month>\d{2})-"
    r"(?P<day>\d{2})"
)


def parse_iso_date(value: str) -> date:
    match = DATE_PATTERN.fullmatch(value)
    if match is None:
        raise ValueError("Expected YYYY-MM-DD")

    parts = {
        name: int(number)
        for name, number in match.groupdict().items()
    }
    return date(**parts)


assert parse_iso_date("2026-11-17") == date(2026, 11, 17)

try:
    parse_iso_date("2026-02-30")
except ValueError:
    pass
else:
    raise AssertionError("Impossible date was accepted")

This separation is useful for dates, URLs, email addresses, numeric ranges, and structured data generally: use regex to recognize a small lexical structure, then use the appropriate parser or domain logic to interpret it.

Compile and compose patterns safely

re.compile() creates a reusable pattern object:

import re

ERROR_CODE = re.compile(r"ERR-\d{4}")

messages = [
    "ERR-1024: timeout",
    "OK",
    "ERR-2048: unavailable",
]

codes = [
    match.group()
    for text in messages
    if (match := ERROR_CODE.search(text)) is not None
]

assert codes == ["ERR-1024", "ERR-2048"]

Compiled patterns give important expressions a name and keep their flags together. Python also caches recently used patterns passed to module-level functions, so explicit compilation is not automatically a performance improvement for every program.

Escape dynamic literal text

If external text should be matched literally rather than interpreted as regex syntax, pass it through re.escape():

import re

literal = "file.txt"
pattern = re.compile(re.escape(literal))

assert pattern.findall("file.txt fileXtxt") == ["file.txt"]

Without escaping, the period would match any character.

re.escape() is for pattern fragments, not replacement strings. If a replacement must be inserted literally, a replacement function is often the safest option because its return value is used directly:

import re

replacement = r"\archive\1"
result = re.sub(r"TARGET", lambda match: replacement, "TARGET")

assert result == replacement

Avoid constructing a regex from user input when the user only intended a literal search.

Prevent catastrophic backtracking

Python’s standard re engine uses backtracking. Some ambiguous patterns can take exponentially longer as the input grows.

A classic dangerous shape is:

^(a+)+$

A long sequence of a characters followed by a different character nearly matches. The engine may try many ways of dividing the same characters between the nested repetitions before concluding that the match fails.

This becomes a regular expression denial-of-service vulnerability when an attacker controls the input, the pattern, or both. Python’s built-in re API does not provide a per-match timeout.

Defensive practices include:

  • Avoid nested quantifiers and overlapping alternatives when the same characters can be matched in several ways.
  • Limit input length before applying a pattern.
  • Test long near-matches, not only successful inputs.
  • Do not accept arbitrary user-supplied patterns unless they run under appropriate isolation or a constrained engine.
  • Prefer a linear-time regex engine when its supported feature set meets the requirement.
  • Use atomic groups or possessive quantifiers only after verifying that their changed semantics are correct.
  • Keep expensive testing away from production and shared environments.

Length limits are defense in depth, not a substitute for fixing an ambiguous pattern. Conversely, a pattern that looks suspicious is not automatically exploitable; performance depends on the complete expression and the failing input.

Common mistakes

Accepting a valid substring

import re

assert re.search(r"\d+", "abc123xyz") is not None

This proves only that the string contains digits. It does not validate a numeric input. Use fullmatch() when the entire value must satisfy the pattern.

Forgetting that a match may be empty

import re

match = re.search(r"\d*", "abc")
assert match is not None
assert match.group() == ""
assert match.span() == (0, 0)

“No match” and “a zero-length match” are different results.

Changing findall() accidentally

Adding capturing parentheses can change findall() from returning complete matches to returning captured values. Use (?:...) for structural grouping when the captured text is not required.

Treating regex as a universal parser

Prefer dedicated libraries for JSON, CSV, dates, URLs, markup, and programming languages. Regular expressions work best for bounded lexical patterns, not arbitrary nested structures.

Assuming every regex dialect is identical

Syntax and behavior vary between Python, JavaScript, Java, PCRE, .NET, Rust, and other engines. Even familiar features such as anchors, Unicode classes, backreferences, and lookbehind can differ.

Recent version changes worth knowing

Python’s regex API continues to evolve:

  • Python 3.11 added atomic groups and possessive quantifiers.
  • Python 3.12 began issuing SyntaxWarning for unrecognized escape sequences in ordinary string literals.
  • Python 3.13 introduced re.PatternError as the preferred exception name; re.error remains an alias. It also deprecated passing maxsplit and flags positionally to re.split().
  • Python 3.14 added \z as an unambiguous end-of-string anchor and made \B match an empty input string.
  • Python 3.15 added prefixmatch() and soft-deprecated the less explicit match() name without planning its removal.

When supporting several Python versions, keep the oldest supported interpreter in mind before adopting new syntax.

A practical test checklist

Before shipping a regular expression, verify:

  1. Normal valid input produces the intended result.
  2. Clearly invalid input is rejected.
  3. Extra leading or trailing characters cannot slip through.
  4. Empty strings and zero-length matches behave as expected.
  5. Newlines, punctuation, and Unicode follow the intended policy.
  6. Capturing groups produce the expected return shape.
  7. Long near-matches complete in acceptable time.
  8. A string method or dedicated parser would not be clearer.

A compact assertion suite is often enough to expose boundary mistakes:

import re

USERNAME = re.compile(
    r"[a-z][a-z0-9_]{2,19}",
    re.IGNORECASE | re.ASCII,
)

valid = ["alice", "user_42", "Bob123"]
invalid = [
    "ab",
    "42alice",
    "name-with-dash",
    "user name",
    "alice!",
]

for value in valid:
    assert USERNAME.fullmatch(value), value

for value in invalid:
    assert USERNAME.fullmatch(value) is None, value

Conclusion

Regular expressions are most effective when they solve a specific, bounded text-processing problem. Start with the smallest useful pattern, choose the operation whose scope matches the task, and test both successful input and realistic failures.

The most important distinctions are simple:

  • search() locates a match anywhere.
  • prefixmatch()—or match() on older Python versions—checks the beginning.
  • fullmatch() validates the complete input.
  • Unicode is the default for str patterns; ASCII must be selected deliberately.
  • Complex or security-sensitive patterns require correctness and performance tests.

References

  • Python: re — Regular expression operations - docs[.]python[.]org/3.15/library/re.html
  • Python: Regular expression HOWTO - docs[.]python[.]org/3.15/howto/regex.html
  • Python: What’s new in Python 3.15 - docs[.]python[.]org/3.15/whatsnew/3.15.html
  • Python: What’s new in Python 3.14 - docs[.]python[.]org/3.15/whatsnew/3.14.html
  • Python: Lexical analysis - docs[.]python[.]org/3.15/reference/lexical_analysis.html
  • OWASP: Denial of Service Cheat Sheet - cheatsheetseries[.]owasp[.]org/cheatsheets/Denial_of_Service_Cheat_Sheet.html
  • OWASP: Regular Expression Denial of Service - wstg[.]owasp[.]org/latest/4-Web_Application_Security_Testing/07-Injection/28-Regular_Expression_Denial_of_Service/

Post a Comment

0 Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

This site uses cookies from Google to deliver its services and analyze traffic. Your IP address and user-agent are shared with Google along with performance and security metrics to ensure quality of service, generate usage statistics, and to detect and address abuse. More Info
Ok, Go it!