2011-12-23 69 views
0

可能重複:
Strip html from strings in python
RegEx match open tags except XHTML self-contained tags在正則表達式中刪除HTML標籤

我的正則表達式模式在我的Python模塊,將刪除指定字符串的HTML標記。

它不適用於這種情況。

輸入字符串:

string=<li class=" 
     tal 
    "><h3><a href="/aclk?sa=l&amp;ai=CoS4y-Wz0TrnqC8y0rAfysK2DB46PiJECzoK8_yKPwd4FCAAQAigCUL7Kz4P9_____wFg5erjg5gOoAH0m_XuA8gBAakCoqvilYNWVD6qBB1P0Dm6CNzrf62IC36fDvUIh77EpeheIRdH_YEaPw&amp;sig=AOD64_2z9xPK8vOxUCpIGTjBcc2Lg-GAeA&amp;adurl=http://www.policybazaar.com/creditcards/creditcard-india.aspx%3Futm_source%3Dgoogle%26utm_medium%3Dppc%26utm_term%3DCreditcard_delhi_only%26utm_campaign%3Dcredit_card" id="pa2">Compare <b>Credit Cards</b> | PolicyBazaar.com</a></h3>Get Best <b>Credit Card</b> For Free, Now U Have a Choice, Choose wisely!<br /><cite>www.policybazaar.com/<b>credit</b>-<b>Cards</b></cite></li> 

正則表達式:

In [64]:p = re.compile(r'<.*?>') 
In [65]:text=p.sub('',str(string)) 
In [66]: text 
Out[66]: '<li class="\n   tal\n  ">Compare Credit Cards | PolicyBazaar.comGet Best Credit Card For Free, Now U Have a Choice, Choose wisely!www.policybazaar.com/credit-Cards' 

結果有<li>標籤依然。不管這個類名稱和字符串模式如何刪除。

回答

4

在這種情況下,你應該使用DOTALL功能:

p = re.compile(r'<.*?>',re.DOTALL) 

應該工作。

但是......你不應該使用正則表達式的HTML解析,看到這一點:https://stackoverflow.com/a/1732454/11621

HTH。

+1

+1但是,代替'。*?'lazy-dot-star,更快,更準確的表達式是:'p = re.compile(r'<[^>] *>')',或者更好:'p = re.compile(r「」「''] + |」[^「] *」|'[^'] *')*>「」「)',允許帶尖括號的屬性。但正如其他人指出的,所有這些正則表達式仍然可能失敗。最好使用專爲工作而設計的工具解析HTML(正如Zsolt Botykai在此答案中正確指出的那樣)。 – ridgerunner 2011-12-23 17:26:33

+0

@ridgerunner關於尖括號的TIL在屬性中是允許的,哇:-)而且你是對的,你的正則表達式更準確。我只應該工作:-) – 2011-12-23 18:41:33

2

谷歌或搜索HTML和正則表達式的Stackoverflow - 這是一個壞主意。你最好使用Beautiful Soup或其他一些真正的HTML解析器並修改DOM。

+3

我用美麗的湯爲HTML解析。工作得很好。 – 2011-12-23 13:59:03