正規表現メモ

要求仕様

  • Index_(N)という部分列が複数含まれた文字列が渡されるので、その部分をIndices_(N+1)と書き換える

実装

import re

string = "abcIndex_1:Index_2:Index_3---Index_100xyz"

rex = "Index_([0-9]+)"
robj = re.compile(rex)

temp = string
ret = ""
while True:
    mch = robj.search(temp)
    if not mch: break
    ret += temp[:mch.start()] # start()でマッチ部分列の先頭文字のインデックス
    ret += "Indices_%d" % (int(mch.expand(r"\1")) + 1) # expand()で置換の結果
    temp = temp[mch.end():] # end()でマッチ部分列の最終文字のインデックスk
ret += temp

print ret