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