我有一个字符串:
st = "Dee Fee, MD is a good person. Kas Egre, MD came here"
我想将", MD"
替换为"Name:"
并将其放在名称之前,因此新字符串应为:
new = "Name: Dee Fee is a good person. Name: Kas Egre came here"
我编写以下代码,它可以工作,但它没有给出我想要的东西。结果如下:
Name: Dee Fee, MD is a good person. Name: Dee Fee, MD came here
Name: Kas Egre, MD is a good person. Name: Kas Egre, MD came here
这是我的代码:
rename = re.compile(r"""([A-Z][a-z]+\s[A-Z\s]*[A-Z][a-z]+)(,\s)(MD)""")
match = rename.search(st)
for match in rename.finditer(st):
if match.group(3) == 'MD':
new = rename.sub("Name: %s"%(match.group(0)),st)
print new
如何修复我的代码?谢谢你的帮助
答案 0 :(得分:1)
稍微简化你的正则表达式......
>>> re.sub(r'(\w+\s+\w+),\s*MD', lambda x: 'Name: '+ x.group(1), st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'
实际上,我们甚至不需要这里的函数,因为我们可以插入\N
组(其中N是组号)......
>>> re.sub(r'(\w+\s+\w+),\s*MD', r'Name: \1', st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'
答案 1 :(得分:0)
将re.sub
与捕获组一起使用:
>>> import re
>>> st = "Dee Fee, MD is a good person. Kas Egre, MD came here"
>>> rename = re.compile(r'([A-Z][a-z]+\s+[A-Z][a-z]+),\s*\bMD\b')
>>> rename.sub(r'Name: \1', st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'
替换字符串中的 \1
将替换为第一个捕获的组(名称部分)。