如何匹配图像标记的链接与正则表达式

时间:2011-02-06 02:49:14

标签: python 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>

1 个答案:

答案 0 :(得分:1)

规则#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!!" />

<强> Edit4:

>>> 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

仍然有效;你确定你想要匹配的网址值是否正确?