用正则表达式替换两个标签之间的内容
如果我有一个xml标签,比如:
<tag>
... abunch of stuff inside here
</tag>
我该怎么把里面的内容全部去掉,包括标签本身呢?
我试过用 re.sub('<tag>.+</tag>', '', string)
,但是没有成功。我哪里出错了呢?
3 个回答
-2
我之前其实用过xml,不过已经很久了。当时我在使用svg,并且在处理编辑svg。如果你想删除标签里面的内容,我觉得你应该去看看javascript或者jquery的相关内容。
5
你不能用正则表达式来解析XML。这根本不可能。很多人写的正则表达式看起来能用,但一旦遇到一些意想不到的情况就会出问题。你真的需要使用专门的XML解析器来处理这个。
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>