On this page
  1. sre_compile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Inspecting Compiled Regex Bytecode Safely
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

sre_compile

Prev: sqlite3 | Up: stdlib_module | Next: sre_constants
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — sre_compile
Tags: #public #python3 #stdlib


Import

import sre_compile

Overview

Internal regular-expression bytecode compiler formerly backing the re module (deprecated since Python 3.11 in favor of the private re._compiler module). Never import sre_compile in new code—always go through re (re.compile()).

Quick Start

import re

# Public API (re.compile) delegates to the internal regex compiler
pattern = re.compile(r"(?P<word>\w+)=(\d+)")
m = pattern.match("score=42")
assert m is not None and m.group("word") == "score"

Implementation Walkthrough

1. Inspecting Compiled Regex Bytecode Safely

Instead of importing sre_compile, pass re.DEBUG to re.compile() when you want to see the parsed tree and compiled opcode structure of a regular expression:

import contextlib
import io
import re

buf = io.StringIO()
with contextlib.redirect_stdout(buf):
    re.compile(r"[a-z]+\d?", re.DEBUG)

assert "MAX_REPEAT" in buf.getvalue()

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes