Possessive Quantifiers Stop Backtracking
Use possessive quantifiers in Python regex to stop catastrophic backtracking on hostile input, and measure the difference against greedy groups.
Code
import re
import time
hostile = 'a' * 16 + '!'
greedy = re.compile(r'(a+)+b')
# 占有量词 a++:吃掉字符后不再吐出,嵌套分组无法指数级回溯
sticky = re.compile(r'(a++)+b')
start = time.perf_counter()
print('greedy match:', bool(greedy.match(hostile)))
greedy_ms = (time.perf_counter() - start) * 1000
start = time.perf_counter()
print('possessive match:', bool(sticky.match(hostile)))
sticky_ms = (time.perf_counter() - start) * 1000
print(f'greedy={greedy_ms:.2f}ms possessive={sticky_ms:.2f}ms')Output
Captured from a sandboxed run of this snippet in the build pipeline.
greedy match: False
possessive match: False
greedy=2.87ms possessive=0.00msInside the snippet
Module-level bindings hold the data — hostile, greedy, sticky, start — with no function scope in between.
Putting it to use
Look for the greedy match:, possessive match:, greedy= prefixes when the file runs; they tie each line to its step.
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
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `re`, `time`. Its state lives in module-level bindings: `hostile`, `greedy`, `sticky`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.