Skip to main content
 首页 » 编程设计

Python 正则表达式卡住输入字符串小

2025年04月02日24TianFang

我在一堆维基百科页面上使用正则表达式。实际上,前 20 页的工作真的很好,但后来突然卡住了,我看不出任何原因。中断脚本提供了这个:

File "imageListFiller.py", line 30, in getImage 
foundImage = re.search(urlRegex, str(decodedLine)) 
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/re.py",line 173, in search 
return _compile(pattern, flags).search(string) 

这是我的代码:

def getImage(wikiHtml):   
    urlRegex = """File:((?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:[0-9a-fA-F][0-9a-fA-F]))*?\.(png|jpg|svg|JPG))""" 
uselessPictures = ("Wiktionary-logo-v2.svg", "Disambig_gray.svg", 
                   "Question_book-new.svg", "Commons-logo.png")     
 
for line in wikiHtml: 
    decodedLine = line.decode('utf-8') 
    foundImage = re.search(urlRegex, str(decodedLine)) 
    if foundImage: 
        if not foundImage.group(1) in uselessPictures: 
            return foundImage.group(1) 

这是导致它卡住的输入字符串:

href="/wiki/File:EARTH_-_WIKIPEDIA_SPOKEN_ARTICLE_(Part_01).ogg" title="Listen to this article"> src="//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/20px-Sound-icon.svg.png" width="20" height="15" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/30px-Sound-icon.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/40px-Sound-icon.svg.png 2x" data-file-width="128" data-file-height="96" > />

正则表达式实际上不应该在这里匹配,它只需要跳过这一行。 谢谢!

请您参考如下方法:

模式中的 $-_ 部分创建了一个范围匹配大写字母和数字,甚至更多的字符。由于该组中的其他替代分支可能在同一位置匹配(如 [a-zA-Z]),导致超时/灾难性回溯问题。

您只需要连接所有仅匹配第 1 组中 1 个字符的字符类,然后转义字符类中的 - 或将其放在字符类的开头/结尾(如果将来要更新模式,我仍然会逃避它):

r"""File:((?:[0-9a-fA-F]{2}|[a-zA-Z0-9\-$_@.&+!*(),])*?\.(png|jpg|svg|JPG))""" 

参见 regex demo .

此外,较长的备选方案应在较短的备选方案之前,因此 [0-9a-fA-F]{2} 应排在第一位。

此外,\w 可用于稍微缩短模式(替换 [a-zA-Z0-9_]):

r"""File:((?:[0-9a-fA-F]{2}|[\w\-$@.&+!*(),])*?\.(png|jpg|svg|JPG))""" 
                             ^^^