使用正则 清除字符串中 指定标签 以外的所有 html 标签


Python 使用正则 清除字符串中除了 ...... 以外的所有 html 标签



指定标签内无其它标签

import re


def sub_replace(match_obj):
    # print(type(match_obj), match_obj)
    tag = match_obj.group()
    if 'sub>' in tag or 'sup>' in tag:
        return tag


text = "测试--sub标签内容--
测试
--sup标签内容--
测试测
" # re.sub 可传入 一个可调用对象 regex = re.compile(r'(<?[^>]+>)') result = regex.sub(sub_replace, text) print(result) # --sub标签内容----sup标签内容--



指定标签内有其它标签

import re

text = '1111111--sub标签内容--
aaaa
2222222--sup标签内容--
aaaa
' result = re.sub(r'<(?!sup|sub)([^>]+)>.*?', '', text) print(result) # --sub标签内容----sup标签内容--