我有一个相当大的字符串(〜700k),我需要运行10个正则表达式并计算任何正则表达式的所有匹配。我的快速和肮脏的IMPL是像做re.search(“(表达式1)|(表达式2)| ...”),但我想知道,如果我们想在一个循环,而不是匹配看到任何的性能提升:正则表达式'|'运算符vs每个子表达式的单独运行
换句话说,我想比较的性能:
def CountMatchesInBigstring(bigstring, my_regexes):
"""Counts how many of the expressions in my_regexes match bigstring."""
count = 0
combined_expr = '|'.join(['(%s)' % r for r in my_regexes])
matches = re.search(combined_expr, bigstring)
if matches:
count += NumMatches(matches)
return count
VS
def CountMatchesInBigstring(bigstring, my_regexes):
"""Counts how many of the expressions in my_regexes match bigstring."""
count = 0
for reg in my_regexes:
matches = re.search(reg, bigstring)
if matches:
count += NumMatches(matches)
return count
我将不再是懒惰和运行一些测试,明天(和后的结果),但我想知道是否答案会跳出来,真正理解正则表达式如何工作的人:)
因为在他的每一个例子都是正则表达式只使用一次,你不应该获得通过预编译的任何性能改进。即使你使用的每个正则表达式不止一次 – 2009-02-24 09:12:57
,Python的re模块已经缓存编译正则表达式为你,所以在第二次以后它会使用预编译的一个呢。 – nosklo 2009-02-25 14:07:24