Python正则表达式删除所有不在其他两个标记之间的标记

时间:2017-07-06 23:34:34

标签: python html regex

我正在使用python并希望从字符串中删除所有未包含在某些标记中的html标记。在此示例中,我想删除<header>标记</header>中未包含的所有html标记,也不删除该封闭标记。

例如:

<h1>Morning</h1>
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
<h2>Night</h2>

结果:

Morning
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
Night

我花了好几个小时但却没有运气。 我知道以下内容会找到所有标签:

re.sub('<.*?>', '', mystring)

这会在标题标记中找到任何内容:

re.sub('<header>.*?</header>', '', mystring)

但我如何否定它,以便第一个正则表达式忽略第二个正则表达式发现的内容?任何帮助是极大的赞赏!谢谢! :)

1 个答案:

答案 0 :(得分:3)

如Josep Valls在评论中所述,您可以使用BeautifulSoup快速轻松地完成此操作。方法如下:

from bs4 import BeautifulSoup

soup = BeautifulSoup('''<h1>Morning</h1>
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
<h2>Night</h2>''', 'html.parser')

for tag in soup.find_all(recursive=False):
    if not tag.findChildren():
        tag.unwrap()

print(soup)

打印出来:

Morning
<header>
<h1>Afternoon</h1>
<h2>Evening</h2>
</header>
Night
相关问题