【发布时间】:2021-07-30 19:57:04
【问题描述】:
我有一长串句子,我正在尝试使用 ANSI 颜色代码来突出显示匹配的字符串。输入不区分大小写,但我希望输出(即正匹配)保持区分大小写。
#!/usr/bin/env python3
from re import sub, IGNORECASE
red = '\033[31m'
nul = '\033[0m'
sentences = ["foo foo findme 123 bar bar",
"foo findme foo bar 123 bar",
"foo foo FindME 123 bar bar"]
for sentence in sentences:
search_term = "findme 123"
sentence = sub(search_term.replace(' ', '.*'), f'{red}{search_term}{nul}', sentence, flags=IGNORECASE)
print(sentence)
当前输出:
foo foo findme 123 bar bar # this is good
foo findme 123 bar # this is bad
foo foo findme 123 bar bar # this is bad
期望的输出:
foo foo findme 123 bar bar
foo foo FindME 123 bar bar
如何正确匹配区分大小写的字符串并防止误报破坏句子的某些部分?
我非常愿意使用 re 以外的库来解决这个问题,但通常更喜欢纯 python3 方法。
【问题讨论】:
标签: python python-3.x regex string replace