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