MST

星途 面试题库

面试题:Python正则表达式之高级匹配模式 - 专家难度

给定一段HTML代码文本,要求使用Python正则表达式提取出所有标签内的文本内容,并且这些标签需要满足以下条件:标签名称必须是自定义的'custom - tag',标签可以有多个属性,属性值可能包含特殊字符,且属性值中的特殊字符需要按照HTML实体转义规则进行还原。请实现这个功能,返回提取出的文本内容列表,同时要考虑性能优化。
34.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import re
import html

def extract_custom_tag_text(html_code):
    # 定义正则表达式匹配自定义标签及内部文本
    pattern = re.compile(r'<custom - tag(.*?)>(.*?)</custom - tag>', re.DOTALL)
    results = []
    for match in pattern.finditer(html_code):
        # 还原属性值中的HTML实体
        attrs = match.group(1)
        attrs_dict = {}
        if attrs:
            for attr in attrs.split():
                key, value = attr.split('=')
                attrs_dict[key] = html.unescape(value.strip('"'))
        # 还原标签内文本中的HTML实体
        inner_text = html.unescape(match.group(2))
        results.append(inner_text)
    return results

你可以这样调用函数:

html_code = "<custom - tag attr1='value1' attr2='&lt;special char&gt;'>text1</custom - tag><custom - tag attr3='&amp;'>text2</custom - tag>"
print(extract_custom_tag_text(html_code))