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

vjrehmav  于 7个月前  发布在  Python
关注(0)|答案(3)|浏览(56)

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

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

字符串
有没有一种方法可以将这两个合并结合起来,这样我就可以计算我的替换,而不需要两次通过源字符串?
注意事项:我对替换是否匹配不感兴趣,我感兴趣的是同一个调用中匹配的确切计数,避免一个调用count和一个调用substitute。

kuuvgm7e

kuuvgm7e1#

可以使用re.subn

re.subn(pattern, repl, string, count=0, flags=0)

字符串
返回(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

ggazkfy8

ggazkfy82#

您可以在调用re.sub函数的同时传递repl函数。* 该函数接受单个匹配对象参数,并返回替换字符串。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

7rtdyuoh

7rtdyuoh3#

import re

text = "Jack 10, Lana 11, Tom 12"
count = len([x for x in re.finditer(r"(\d+)", text)])
print(count)

# Output: 3

字符串
好吧,有个更好的办法

import re

text = "Jack 10, Lana 11, Tom 12"
count = re.subn(r"(\d+)", repl="replacement", string=text)[1]
print(count)

# Output: 3

相关问题