gpt4 book ai didi

Python:计算并替换同一次正则表达式?

转载 作者:行者123 更新时间:2023-12-03 23:08:14 24 4
gpt4 key购买 nike

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

for match in re.finditer(): count++

有没有办法将这两者结合起来,这样我就可以计算我的替换而无需两次遍历源字符串?

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

最佳答案

您可以通过 repl调用 re.sub 时的函数功能。
该函数采用单个匹配对象参数,并返回替换字符串。 repl每个不重叠的模式都会调用函数。

试试这个:

count = 0
def count_repl(mobj): # --> mobj is of type re.Match
global count
count += 1 # --> count the substitutions
return "your_replacement_string" # --> return the replacement string

text = "The original text" # --> source string
new_text = re.sub(r"pattern", repl=count_repl, string=text) # count and replace the matching occurrences in one pass.

或,

您可以使用 re.subn执行与 re.sub 相同的操作, 但返回一个元组 (new_string, number_of_subs_made)。
new_text, count = re.sub(r"pattern", repl="replacement", string=text)

示例:
count = 0
def count_repl(mobj):
global count
count += 1
return f"ID: {mobj.group(1)}"

text = "Jack 10, Lana 11, Tom 12, Arthur, Mark"
new_text = re.sub(r"(\d+)", repl=count_repl, string=text)

print(new_text)
print("Number of substitutions:", count)

输出:
Jack ID: 10, Lana ID: 11, Tom ID: 12
Number of substitutions: 3

关于Python:计算并替换同一次正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60897536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com