You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中匹配列表子串并在原字符串中高亮显示的实现方法

Python多子串匹配高亮实现方案

问题分析

你之前的代码存在三个核心问题:

  • str.replace()仅支持固定字符串替换,无法识别|代表的多模式正则语法
  • 没有对高亮列表按长度降序排序,会出现长匹配项被短匹配项拆分的问题,比如catdog会被拆成cat+dog分别高亮
  • 替换逻辑错误,直接把整个原字符串塞进了替换模板,没有取匹配到的子串

实现代码

使用Python标准库re(正则模块)即可实现,不需要额外安装依赖:

1. 生成HTML加粗高亮效果(和你示例输出一致)

import re

highlight_list = ['cat','dog','catdog']
text_main = 'The cat and the dog were dancing together.  They looked like a catdog, not a dogcat'

# 高亮列表按长度降序排序,保证长子串优先匹配
highlight_sorted = sorted(highlight_list, key=lambda x: len(x), reverse=True)
# 拼接正则模式,re.escape避免高亮内容含特殊字符导致匹配错误
pattern = re.compile('|'.join(map(re.escape, highlight_sorted)))

# 替换匹配到的内容为加粗格式
text_highlight = pattern.sub(lambda match: f'<strong>{match.group()}</strong>', text_main)
print(text_highlight)

运行输出:

The <strong>cat</strong> and the <strong>dog</strong> were dancing together.  They looked like a <strong>catdog</strong>, not a dogcat

2. 生成终端黄背景高亮效果

如果需要在终端输出醒目的高亮效果,替换sub的回调函数即可:

# 43代表黄色背景,30代表黑色文字,\033[0m是重置样式避免后续内容也被高亮
text_highlight = pattern.sub(lambda match: f'\033[43;30m{match.group()}\033[0m', text_main)
print(text_highlight)

内容的提问来源于stack exchange,提问作者clg4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 17:51:03