Typing Stubs for regex
types-regex provides static type annotations (stubs) for the `regex` package, an alternative regular expression module for Python. It is part of the typeshed project and allows type checkers like Mypy and Pyright to perform static analysis on code using the `regex` library. The current version is 2026.4.4.20260408, and stub packages from typeshed are automatically released, often multiple times a day, to keep up with runtime library changes.
Warnings
- gotcha The `types-regex` package only provides type annotations. The actual `regex` runtime library must be installed separately alongside `types-regex` for your code to function at runtime.
- gotcha The versioning of `types-regex` (e.g., `X.Y.Z.YYYYMMDD`) indicates that it provides stubs for `regex` version `X.Y.Z` and was released on `YYYYMMDD`. Ensure that your installed `types-regex` version is compatible with your `regex` runtime library version to avoid type-checking errors.
- gotcha Updates to type stubs, even minor ones, can sometimes introduce changes that cause existing code to fail type checking, especially if the underlying library's API has implicit changes not reflected in older stubs, or if stricter types are added.
- gotcha When defining regular expression patterns in Python, it's a best practice to use raw string notation (prefixing the string literal with `r`, e.g., `r"\d+"`). This prevents backslashes from being interpreted as Python escape sequences, which can lead to unexpected behavior or `SyntaxWarning` / `SyntaxError` with invalid escape sequences.
Install
-
pip install types-regex regex
Imports
- regex
import regex
- Match
from regex import Match
- Pattern
from regex import Pattern
Quickstart
import regex
from regex import Pattern, Match
def find_first_email(text: str) -> str | None:
# Compile the regex pattern with type annotation
email_pattern: Pattern[str] = regex.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
# Search for the pattern in the text
match: Match[str] | None = email_pattern.search(text)
if match:
return match.group(0) # Return the entire matched string
return None
text_data = "Contact us at info@example.com or support@test.org for assistance."
first_email = find_first_email(text_data)
if first_email:
print(f"Found email: {first_email}")
else:
print("No email found.")