我有一個有點複雜的正則表達式,我試圖匹配長字符串(65,535個字符)。我正在尋找字符串中re的多次出現,所以我使用finditer。它可以工作,但由於某種原因,它會在識別出前幾次事件後掛起。有誰知道這可能是爲什麼?這裏的代碼片段:finditer在匹配長字符串時掛起
pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)"
matches = re.finditer(pattern, string)
for match in matches:
print "(%d-%d): %s" % (match.start(), match.end(), match.group())
它打印出前四次出現,但然後它掛起。當我使用Ctrl-C殺死它,它告訴我它在迭代器喪生:
Traceback (most recent call last):
File "code.py", line 133, in <module>
main(sys.argv[1:])
File "code.py", line 106, in main
for match in matches:
KeyboardInterrupt
如果我用一個簡單的重新嘗試,它工作正常。
我在運行在Windows XP上的Cygwin上的python 2.5.4上運行它。
我設法讓它掛上一個非常短的字符串。
ddddddeddbedddbddddddddddddddddddddddddddddddddddd
有了它,花了大約15秒返回(並顯示沒有比賽)這個39字符串:
ddddddeddbedddbdddddddddddddddddddddddd
而與此有了這個50字符串,它從來沒有約5分鐘後返回字符串它立即返回:
ddddddeddbedddbdddddddddddddd
謝謝 - 這很有幫助。我可以消除|只是有幾個單獨的正則表達式。我可能會問一個關於刪除d *的新問題 - 我基本上希望正則表達式在任何位置都接受'd'。 – Ben 2009-04-16 09:42:29
@Ben:那只是測試模式之前從字符串D的。 – Gumbo 2009-04-16 09:48:20