Python regex replace nth match

WARNING: This article may be obsolete
This post was published in 2021-09-28. Obviously, expired content is less useful to users if it has already pasted its expiration date.

注:本文仅仅阐述一种(在某些特定场景下可能有作用)的方法。
 def replacenth(string, regex_sub, wanted, n) :替换字符串 string 里的 第n个 regex匹配项,把 第n个regex_sub 替换为 wanted  .
# 修改自:https://stackoverflow.com/a/35091558
import re


# n: nth replace string, n > 0 
# 你需要输入合适的n以避免发生index越界
def replacenth(string, sub, wanted, n):
    indexes = [0]
    where = [(m.start(0), m.end(0)) for m in re.finditer(sub, string)]
    for item in where:
        indexes.append(item[0])
    indexes.append(string.__len__() - 1)
    before = string[:indexes[n]]
    after = string[indexes[n + 1] + 1:]
    replace_string = string[indexes[n]:indexes[n + 1] + 1]
    sub_n = re.sub(sub, wanted, replace_string)
    return before + sub_n + after


# 实际使用的时候(由于场景需要)你要先在这里先写一些regex代码,找到合适的n value

print(replacenth("aa7bb7cc7dd7", re.compile(r'\d'), '9', 3))

结果为:

aa7bb7cc7dd9

Leave a Comment Anonymous comment is allowed / 允许匿名评论