python一个一个替换正则表达式匹配的字符
大家都知道怎么用python的re.sub替换所有的字符串,如果是一个一个替换呢?
我提供一个python2的解决方案
import re
def onebyone_replace(string,index):
pattern = re.compile(ur'\d')
if pattern.search(string[index:])==None:
return
else:
start_index,end_index=pattern.search(string[index:]).span()
new_string=pattern.sub('niexinming',string[index:],1)
print string[:index]+new_string
onebyone_replace(string,index+end_index)
onebyone_replace("1-2-3",0)
结果是:
niexinming-2-3
1-niexinming-3
1-2-niexinming