re#

Python’s built-in module for regular expressions.

Basic Functions#

  • re.compile(pattern: str, flags: int = 0) -> re.Pattern: Compiles a regex string into a reusable re.Pattern object.
  • re.search(pattern: str, string: str, flags: int = 0) -> re.Match | None: Scans through string for the first location where pattern matches.
  • re.match(pattern: str, string: str, flags: int = 0) -> re.Match | None: Checks for a match only at the beginning of string.
  • re.fullmatch(pattern: str, string: str, flags: int = 0) -> re.Match | None: Checks whether the entire string matches pattern.
  • re.finditer(pattern: str, string: str, flags: int = 0) -> Iterator[re.Match]: Returns an iterator yielding re.Match objects over all non-overlapping matches.
  • re.findall(pattern: str, string: str, flags: int = 0) -> list[str] | list[tuple[str, ...]]: Returns all non-overlapping matches as a list of strings (0 or 1 capturing group) or tuples (multiple capturing groups).
  • re.sub(pattern: str, repl: str | Callable[[re.Match], str], string: str, count: int = 0, flags: int = 0) -> str: Replaces matches with repl and returns the new string.
  • re.split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0) -> list[str]: Splits string by occurrences of pattern.

Flags#

Passed via the flags parameter in module-level functions and re.compile(). Combine multiple flags with the bitwise OR operator |.

  • re.IGNORECASE / re.I: Case-insensitive matching
  • re.MULTILINE / re.M: Makes ^ and $ match the start and end of each line
  • re.DOTALL / re.S: Makes . match any character including newline \n
  • re.VERBOSE / re.X: Ignores whitespace and # comments inside the pattern for multi-line formatting
  • re.ASCII / re.A: Restricts \w, \d, and \s to ASCII-only matching instead of Unicode

eg. re.search(r"^error", text, re.I | re.M)

re.compile#

Module-level functions (re.search, re.findall, etc.) look up an internal cache on every call. Precompiling a re.Pattern object with re.compile() provides three advantages:

  • Loop Performance: Eliminates repeated wrapper function calls and cache lookup overhead when scanning millions of lines in a loop.
  • Flag Binding: Binds flags like re.I directly into a reusable re.Pattern constant.
  • Substring Bounds (pos, endpos): Unlocks pos and endpos index parameters not available on module-level functions, avoiding slice allocations.

eg.

import re

LOG_RE = re.compile(r'^(\S+) .* "(GET|POST) (\S+)"', re.I)

for line in lines:
    if m := LOG_RE.search(line):
        print(m.group(3))

re.Pattern Methods#

Module-level functions internally delegate to re.compile(pattern, flags).<method>(...), so behavior is identical. Only two signature rules change:

  • Omitted Arguments: Provides the same 7 methods (search, match, fullmatch, finditer, findall, sub, split) with pattern and flags omitted since they are already bound to the re.Pattern instance.
  • Slice Bounds (pos, endpos): The 5 search methods (search, match, fullmatch, finditer, findall) accept (string: str, pos: int = 0, endpos: int = sys.maxsize) to restrict matching to [pos, endpos) (sub and split do not take pos/endpos).

eg.

import re

TOKEN_RE = re.compile(r"\d+")
line = "id=42, cost=150, retry=3"

# Search starting at index 7 without allocating line[7:]
m = TOKEN_RE.search(line, pos=7)
if m:
    print(m.group(0))  # 150

re.Match Methods#

Methods on an m: re.Match object returned when search, match, or finditer succeeds. Capturing groups (...) are numbered starting from 1 in left-to-right order of opening parentheses.

  • m.group(group: int = 0) -> str: Returns the matched string for the specified group.
    • m.group() / m.group(0): Entire matched string
    • m.group(1), m.group(2), …: Substring matched by the 1st, 2nd (...) capturing group
    • m.group(1, 2): Passing multiple group indices returns a tuple[str, ...]
  • m.groups(default: str | None = None) -> tuple[str | None, ...]: Returns all capturing groups from 1 onward as (m.group(1), m.group(2), ...) (excludes group 0).
  • m.start(group: int = 0) -> int / m.end(group: int = 0) -> int: Returns the start and end indices of the specified group.
  • m.span(group: int = 0) -> tuple[int, int]: Returns the (start, end) index tuple of the specified group.

Examples#

Using re.Match Methods#

import re

text = "Contact: 010-1234-5678"
match = re.search(r"(\d{3})-(\d{4})-(\d{4})", text)

if match:
    print(match.group(0))     # 010-1234-5678 (entire match)
    print(match.group(1))     # 010           (1st group)
    print(match.group(2))     # 1234          (2nd group)
    print(match.group(1, 2))  # ('010', '1234')
    print(match.groups())     # ('010', '1234', '5678')
    print(match.span())       # (9, 22)

finditer and findall#

import re

text = "apple, orange, banana"

# finditer: returns iterator of Match objects
matches = re.finditer(r"\w+", text)
for m in matches:
    print(m.group())

# findall: returns list of strings
fruits = re.findall(r"\w+", text)
print(fruits)  # ['apple', 'orange', 'banana']

See General Regular Expression Concepts