python依次替换正则表达式匹配的字符

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章