【发布时间】:2017-01-29 21:44:30
【问题描述】:
我在一堆维基百科页面上使用正则表达式。实际上对于第一个像 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="收听这篇文章"> 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" 数据文件-width="128" 数据文件高度="96" > />
正则表达式实际上不应该在这里匹配,它只需要跳过这一行。 谢谢!
【问题讨论】:
-
仅供参考:请注意,
[$-_]匹配所有大写 ASCII 字母和数字等。如果你避开连字符,它已经安全得多了。 -
你(或更好的表达方式)容易发生灾难性的回溯:regex101.com/r/eH4nJ2/1
-
为什么不简单地
([^/]*\.(png|jpg|svg|JPG))