本文介绍如何精准匹配常见的成对 html 标签(如 `
在处理 HTML 片段时,若目标是提取特定成对标签的完整结构(例如
e.findall() 进行匹配(match)而非分割(split)。核心思路是:利用正则中的捕获组 + 反向引用,确保开闭标签名称一致,并匹配二者之间的内容。推荐正则模式如下:
import re pattern = r"<(p|li|ul|ol|dl|h1|h2|h3|h4|h5|h6)>[^<]*\1>" subject = 'Some text some text some text.
Another text another text
.
Some text some text some text.
', # 'Another text another text
', # '✅ 关键说明:
⚠️ 重要注意事项:
)或嵌套结构(如
text
from bs4 import BeautifulSoup
soup = BeautifulSoup(subject, 'html.parser')
for tag in soup.find_all(['p', 'li', 'ul', 'ol', 'dl', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
print(tag)✅ 总结:正则适用于可控、结构简单的 HTML 片段提取;生产环境或复杂 HTML,请务必转向 DOM 解析器——它语义准确、容错性强,且天然支持属性遍历、嵌套查询与安全清理。