Regex Timeout Guard for Untrusted Input
Run operator-supplied regular expressions with the regex module timeout, an input length cap, and explicit failure handling.
Code
import regex
USER_PATTERN = regex.compile(
r"^(?P<user>[a-z0-9_]{3,32})@(?P<domain>[a-z0-9.-]{1,120})$"
)
def safe_fullmatch(
pattern: regex.Pattern,
text: str,
*,
timeout: float = 0.05,
max_length: int = 4096,
) -> regex.Match | None:
if len(text) > max_length:
raise ValueError(f"input length {len(text)} exceeds {max_length}")
try:
return pattern.fullmatch(text, timeout=timeout)
except TimeoutError as error:
raise TimeoutError("pattern evaluation exceeded the time budget") from error
if __name__ == "__main__":
match = safe_fullmatch(USER_PATTERN, "ada_lovelace@example.com")
assert match is not None
print(match.group("user"), match.group("domain"))
try:
safe_fullmatch(USER_PATTERN, "x" * 5000)
except ValueError as error:
print("rejected:", error)
evil = regex.compile(r"^(a+)+$")
try:
safe_fullmatch(evil, "a" * 4000 + "b", timeout=0.001)
except TimeoutError as error:
print("timeout:", error)
How the snippet works
Count the function safe_fullmatch as the entire surface area of Regex Timeout Guard for Untrusted Input.
A ValueError and TimeoutError is raised inside an except block, so it is conditional on that failure being handled in the first place.
What to watch for
- Dependency check:
regex— not built-in, must be present in the project. - The guard
len(text) > max_lengthshort-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def safe_fullmatch( pattern: regex.Pattern, text: str, *, timeout: float = 0.05, max_length: int = 4096, ) …
The demo output is labeled (rejected:, timeout:), so every printed line maps back to its originating operation.
Statements that matter
except TimeoutError as error:
raise TimeoutError("pattern evaluation exceeded the time budget") from error
except TimeoutError as error:
print("timeout:", error)
except ValueError as error:
print("rejected:", error)
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- When is the exception raised?
- Inside an `except` handler — the `ValueError` and `TimeoutError` fires only while that failure type is already being handled, not on its own trigger.
- Does this require external packages?
- Yes — `regex`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.