2013-02-08 145 views
0

之間取代一切如果我有一個XML標籤,如:兩個標籤用正則表達式

<tag> 
    ... abunch of stuff inside here 
</tag> 

我如何會刪除裏面的一切,包括標籤本身?我試過re.sub('<tag>.+</tag>', '', string),但它不起作用。我在這裏做錯了什麼?

+2

首先,你應該學習正則表達式解析html的本質[這裏](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – chuwy 2013-02-08 23:42:22

回答

0

你可以安全地做到這一點嗎?與lxml這是違揹你的願望re但你可能已經被其他人的說服說服用re充滿危險。

import lxml.etree as etree 

xml = """<root> 
<item name="1"/> 
<item name="2"/> 
<tag> 
    <nested>Will I die</nested> 
    ... abunch of stuff inside here 
</tag> 
<another/> 
</root>""" 

root = etree.fromstring(xml) 
for to_kill in root.xpath("//tag"): 
    to_kill.getparent().remove(to_kill) 

print etree.tostring(root, pretty_print=True) 

給出:

<root> 
<item name="1"/> 
<item name="2"/> 
<another/> 
</root> 
5

can't用正則表達式解析XML。這是不可能的。許多人創造了似乎可以工作的正則表達式,然後當他們面對任何未曾預料的事情時就立即中斷。您確實需要使用XML解析器來執行此操作。

+0

正如David Schwartz在評論中所說的那樣,人們總是從特定的概念中總結出問題。一般來說,使用正則表達式來破解特定的Xml文件是可以的,但不要指望它在一般情況下工作。 – sotapme 2013-02-08 23:48:34

-2

其實我使用XML之前的工作,但它在很久以前。我正在使用SVG,我正在處理編輯SVG。如果你想刪除標籤內的東西,我相信你應該在javascript或jquery中尋找你的答案。