相关疑难解决方法(0)

1653
推荐指数
16
解决办法
66万
查看次数

为什么在Python中捕获组时正则表达式搜索速度较慢?

我有一个应用程序代码,可以从配置中动态生成正则表达式以进行一些解析.当两个变化的定时性能时,正被捕获的OR正则表达式的每个部分的正则表达式变化明显慢于正常正则表达式.原因是regex模块内部某些操作的开销.

>>> import timeit
>>> setup = '''
... import re
... '''   

#no capture group 
>>> print(timeit.timeit("re.search(r'hello|bye|ola|cheers','some say hello,some say bye, or ola or cheers!')", setup=setup))
0.922958850861

#with capture group
>>> print(timeit.timeit("re.search(r'(hello)|(bye)|(ola)|(cheers)','some say hello,some say bye, or ola or cheers!')", setup=setup))
1.44321084023

#no capture group
>>> print(timeit.timeit("re.search(r'hello|bye|ola|cheers','some say hello,some say bye, or ola or cheers!')", setup=setup))
0.913202047348

# capture group
>>> print(timeit.timeit("re.search(r'(hello)|(bye)|(ola)|(cheers)','some say hello,some say bye, or ola or cheers!')", setup=setup))
1.41544604301
Run Code Online (Sandbox Code Playgroud)

问题:使用捕获组时,导致性能大幅下降的原因是什么?

python regex

18
推荐指数
2
解决办法
1542
查看次数

标签 统计

regex ×2

capturing-group ×1

python ×1

regex-group ×1