我读了一篇很酷的文章,介绍如何避免创建缓慢的正则表达式。通常来说,正则表达式越长、越显式,它就能越快地完成匹配。贪婪的正则表达式可能会慢上数倍。
我想通过对比一个更为复杂/显式语句和一个较不复杂/贪婪语句完成所需时间来测试这一点。大部分情况下似乎都符合这个规律,但是我有一个贪婪语句比较慢。以下是两个例子:
import re
from timeit import timeit
# This works as expected, the explicit is faster than the greedy.
# http_x_real_ip explicit
print(timeit(setup="import re", stmt='''r = re.search(r'(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})', '192.168.1.1 999.999.999.999')''', number=1000000))
1.159849308001867
# http_x_real_ip greedy
print(timeit(setup="import re", stmt='''r = re.search(r'((?:\d{1,3}\.){3}\d{1,3})', '192.168.1.1 999.999.999.999')''', number=1000000))
1.7421739230003368
# This does not work as expected, greedy is faster.
# time_local explicit
print(timeit(setup="import re", stmt='''r = re.search(r'(\d{1,2}/\w{3}/[2][0]\d{2}:\d{2}:\d{2}:\d{2}\s[+][0]{4})', "[23/Jun/2015:11:10:57 +0000]")''', number=1000000))
1.248802040994633
# time_local greedy
print(timeit(setup="import re", stmt='''r = re.search(r'\[(.*)\]', "[23/Jun/2015:11:10:57 +0000]")''', number=1000000))
1.0256699790043058
本地时间正则表达式只是写得很糟糕吗?