如何在python中删除给定开始和结束标记的子字符串?

时间:2012-10-10 17:26:09

标签: python python-2.x

我有一种看起来像是的刺痛:

u'\'\'\'Joseph Michael "Joe" Acaba\'\'\' (born May 17, 1967) is an [[Teacher|educator]], [[Hydrogeology|hydrogeologist]], and [[NASA]] [[astronaut]].<ref name="bio">{{Cite web|url=http://www.jsc.nasa.gov/Bios/htmlbios/acaba-jm.html|title=Astronaut Bio: Joseph Acaba|month=February | year=2006|publisher=[[NASA|National Aeronautics and Space Administration]]|author=NASA|accessdate=November 26, 2006}}</ref><ref name="bio2">{{Cite web|url=http://oeop.larc.nasa.gov/hep/hep-astronauts.html|title=NASA Hispanic Astronauts\n|publisher=National Aeronautics and Space Administration|author=NASA|accessdate=November 26, 2006}}</ref> In May 2004 he became the first person'

我想删除从<refref>的所有测试,包括标记。我是python的新手,我不确定最好的方法。

1 个答案:

答案 0 :(得分:4)

在这种情况下,正则表达式可以正常工作:

import re
ref = re.compile(u'<ref.*?ref>', re.DOTALL)

ref.sub(u'', yourtext)

注意re.DOTALL限定符;您在<ref>部分中有换行符,我们也希望将其删除。

演示:

>>> import re
>>> tst=u'\'\'\'Joseph Michael "Joe" Acaba\'\'\' (born May 17, 1967) is an [[Teacher|educator]], [[Hydrogeology|hydrogeologist]], and [[NASA]] [[astronaut]].<ref name="bio">{{Cite web|url=http://www.jsc.nasa.gov/Bios/htmlbios/acaba-jm.html|title=Astronaut Bio: Joseph Acaba|month=February | year=2006|publisher=[[NASA|National Aeronautics and Space Administration]]|author=NASA|accessdate=November 26, 2006}}</ref><ref name="bio2">{{Cite web|url=http://oeop.larc.nasa.gov/hep/hep-astronauts.html|title=NASA Hispanic Astronauts\n|publisher=National Aeronautics and Space Administration|author=NASA|accessdate=November 26, 2006}}</ref> In May 2004 he became the first person'
>>> ref = re.compile(u'<ref.*?ref>', re.DOTALL)
>>> ref.sub(u'', tst)
u'\'\'\'Joseph Michael "Joe" Acaba\'\'\' (born May 17, 1967) is an [[Teacher|educator]], [[Hydrogeology|hydrogeologist]], and [[NASA]] [[astronaut]]. In May 2004 he became the first person'