← 中文资源

简体中文版本

占有量词阻断灾难性回溯

用 Python 正则的占有量词阻断灾难性回溯:内层量词吃掉字符后不再吐出,恶意长输入也能快速失败,并与贪婪分组做耗时对照。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

greedy match: False
possessive match: False
greedy=2.87ms possessive=0.00ms

实现说明

顶层就这几处状态:hostile、greedy、sticky、start。

使用要点

  • 跑完文件,输出里会留下标记——greedy match:、possessive match:、greedy=。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 全部导入都来自标准库:re、time。 文件用顶层绑定保存自己的状态:hostile、greedy、sticky。

代码示例

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')