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>
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Pepe 2011-02-06 03:27:04
看到我的迴應如下,這也適用於你的典型(如後期)鏈接。這毫無幫助,並且不回答這個問題。對我的問題肯定有一個答案,可以幫助我學習。 – jml 2011-02-06 03:33:29