2011-02-06 18 views
1

我正在研究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

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Pepe 2011-02-06 03:27:04

+0

看到我的迴應如下,這也適用於你的典型(如後期)鏈接。這毫無幫助,並且不回答這個問題。對我的問題肯定有一個答案,可以幫助我學習。 – jml 2011-02-06 03:33:29

回答

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 

仍然有效;你確定你試圖匹配的url值是正確的嗎?

相關問題