Possessive Quantifiers Stop Backtracking

Use possessive quantifiers in Python regex to stop catastrophic backtracking on hostile input, and measure the difference against greedy groups.

PythonSecurity Boundaries

Code

pythonsnippet
18 lines
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.00ms

Inside 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

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`.