我有一個相當大的字符串(〜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