首页 > 解决方案 > 文本中字符串的多次替换,不匹配子字符串

问题描述

我尝试使用正则表达式替换文本中的不同字符串而不匹配子字符串。

我用:

v = {"Anna" : 'UNNK'} 
text2 = "My name is Anna not Maria-Anna"
for i in v.keys():
    w = r"\b{}(?![-|\w*])".format(i)
    reg = re.compile(w)
text3 = reg.sub('UNK', text2) 
print(text3) 

代码返回:

“我的名字是 UNK 不是 Maria-UNK”

我想返回的地方:“我的名字是 UNK 而不是 Maria-Anna”

标签: pythonregex

解决方案


你太复杂了。这可以只使用replace在键和值周围添加空格的字符串来完成,以确保您只替换整个单词(而不是单词内部):

v = {"Anna" : 'UNNK'} 
text2 = "My name is Anna not Maria-Anna"

text2 = f' {text2} '
for k, v in v.items():
    text2 = text2.replace(f' {k} ', f' {v} ')

text2 = text2[1:-1] 
print(text2) 
# My name is UNNK not Maria-Anna

推荐阅读