Python:在同一遍中计算和替换正则表达式?

Mar*_*son 11 python regex

我可以用 全局替换正则表达式re.sub(),并且可以用 来计算匹配数

for match in re.finditer(): count++
Run Code Online (Sandbox Code Playgroud)

有没有办法将这两者结合起来,以便我可以计算替换次数,而无需对源字符串进行两次传递?

注意:我对替换是否匹配不感兴趣,我感兴趣的是同一调用中匹配的确切计数,避免一次调用 count 和一次调用替换。

Ch3*_*teR 8

您可以使用re.subn

re.subn(pattern, repl, string, count=0, flags=0)
Run Code Online (Sandbox Code Playgroud)

它返回(new_string, number_of_subs_made)

出于示例目的,我使用与@Shubham Sharma 使用的示例相同的示例。

text = "Jack 10, Lana 11, Tom 12, Arthur, Mark"
out_str, count = re.subn(r"(\d+)", repl='repl', string=text)

# out_str--> 'Jack repl, Lana repl, Tom repl, Arthur, Mark'
# count---> 3
Run Code Online (Sandbox Code Playgroud)