首页 > 解决方案 > 在python中使用正则表达式和for循环值替换字符串

问题描述

我想使用第二个变量替换第一个变量的值,但我想保留逗号。我使用了正则表达式,但我不知道它是否可能是因为我还在学习它。所以这是我的代码。

import re
names = 'Mat,Rex,Jay'
nicknames = 'AgentMat LegendRex KillerJay'
split_nicknames = nicknames.split(' ')
for a in range(len(split_nicknames)):
    replace = re.sub('\\w+', split_nicknames[a], names)
print(replace)

我的输出是:

KillerJay,KillerJay,KillerJay

我想要这样的输出:

AgentMat,LegendRex,KillerJay

标签: pythonregex

解决方案


我怀疑您正在寻找的内容应该类似于以下内容:

import re

testString = 'This is my complicated test string where Mat, Rex and Jay are all having a lark, but MatReyRex is not changed'
mapping = { 'Mat' : 'AgentMat',
            'Jay' : 'KillerJay',
            'Rex' : 'LegendRex'
}
reNames = re.compile(r'\b('+'|'.join(mapping)+r')\b')
res = reNames.sub(lambda m: mapping[m.group(0)], testString)
print(res)

执行这个会产生映射的结果:

This is my complicated test string where AgentMat, LegendRex and KillerJay are all having a lark, but MatReyRex is not changed

推荐阅读