实现说明
顶层就这几处状态: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')