[英]how to match an image tag's link with regex
我正在使用python中的正则表达式匹配功能。 我有以下代码:
def src_match(line, img):
imgmatch = re.search(r'<img src="(?P<img>.*?)"', line)
if imgmatch and imgmatch.groupdict()['img'] == img:
print 'the match was:', imgmatch.groupdict()['img']
以上似乎对我来说根本无法正常运行。 另一方面,我确实很幸运:
def href_match(line, url):
hrefmatch = re.search(r'<a href="(?P<url>.*?)"', line)
if hrefmatch and hrefmatch.groupdict()['url'] == url:
print 'the match was:', hrefmatch.groupdict()['url']
else:
return None
有人可以解释为什么会这样吗(或者也许看起来两者都应该工作)? 例如,href_match()函数中的标识符是否有特殊之处? 可以假定在两个函数中我都传递了一条包含我要搜索的字符串的行以及该字符串本身。
编辑:我应该提一下,我确定我永远不会得到像这样的标签:
<img width="200px" src="somefile.jpg">
原因是我使用的是正在生成html的特定程序,因此它永远不会产生这样的标签。 在我总是会得到一个像这样的标签的假设下,该示例应被视为纯理论上的:
<img src="somefile.jpg">
编辑:
这是我正在馈送给与输入参数不匹配的函数的行的示例:
<p class="p1"><img src="myfile.anotherword.png" alt="beat-divisions.tiff"></p>
规则#37:请勿尝试使用正则表达式解析HTML。
使用正确的工具进行工作-在这种情况下,为BeautifulSoup。
编辑:
剪切和粘贴功能并进行测试
>>> src_match('this is <img src="my example" />','my example')
the match was: my example
因此它似乎起作用了; 但是,它将在(完全有效的)HTML代码上失败,例如
<img width="200px" src="Y U NO C ME!!" />
编辑4:
>>> src_match('<p class="p1"><img src="myfile.png" alt="beat-divisions.tiff"></p>','myfile.png')
the match was: myfile.png
>>> src_match('<p class="p1"><img src="myfile.anotherword.png" alt="beat-divisions.tiff"</p>\n','myfile.anotherword.png')
the match was: myfile.anotherword.png
仍然有效; 您确定要匹配的url值正确吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.