

新闻资讯
技术学院本文介绍如何通过正则表达式精准匹配成对的 html 标签(如 `
在处理 HTML 片段时,若目标是“按特定成对标记切分字符串并保留标签本身”,直接使用 re.split() 会将分隔符(即标签)从结果中移除,导致结构丢失。例如,用 re.split(r'
正确做法是改用 re.finditer() 或 re.findall() 进行匹配(match)而非分割(split),并构造能捕获开闭标签配对 + 中间内容的正则模式。推荐使用如下表达式:
import re pattern = r"<(p|li|ul|ol|dl|h1|h2|h3|h4|h5|h6)>[^<]*\1>" test_string = 'Some text some text.
Another text
.
Some text some text.
', 'Another text
', '该正则核心解析如下:
⚠️ 注意事项:
✅ 推荐替代方案(BeautifulSoup 示例):
from bs4 import BeautifulSoup soup = BeautifulSoup(test_string, 'html.parser') target_tags = soup.find_all(['p', 'li', 'ul', 'ol', 'dl', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']) result = [str(tag) for tag in target_tags]
综上:正则匹配成对标签是快速原型开发的有效手段,但应明确其局限性;涉及真实 HTML 处理时,请优先选用 DOM 解析器,兼顾健壮性与可维护性。