0

在使用函数时re.sub

import re
def custom_replace(match):
    # how to get the match number here? i.e. 0, 1, 2
    return 'a'
print(re.sub(r'o', custom_replace, "oh hello wow"))

如何获得里面的比赛号码custom_replace

即 0、1、2 表示示例输入字符串的三个“o”。

注意:我不想为此使用全局变量,因为多个此类操作可能发生在不同的线程等中。

4

3 回答 3

1

根据@Barmar 的回答,我尝试了这个:

import re

def custom_replace(match, matchcount):
    result = 'a' + str(matchcount.i)
    matchcount.i += 1
    return result

def any_request():
    matchcount = lambda: None  # an empty "object", see https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python/37540574#37540574
    matchcount.i = 0           # benefit : it's a local variable that we pass to custom_replace "as reference
    print(re.sub(r'o', lambda match: custom_replace(match, matchcount), "oh hello wow"))
    # a0h hella1 wa2w

any_request()

它似乎工作。

原因:我有点不愿意为此使用全局变量,因为我在 web 框架中使用它,在路由函数中(any_request()在此处调用)。
假设有许多并行请求(在线程中),我不希望全局变量在不同调用之间“混合”(因为操作可能不是原子的?)

于 2020-04-07T18:57:39.457 回答
0

似乎没有内置的方法。您可以使用全局变量作为计数器。

def custom_replace(match):
    global match_num
    result = 'a' + str(match_num)
    match_num += 1
    return result

match_num = 0
print(re.sub(r'o', custom_replace, "oh hello wow"))

输出是

a0h hella1 wa2w

每次使用此功能调用时,不要忘记重置match_num为之前。0re.sub()

于 2020-04-07T18:10:07.087 回答
0

您可以re.search使用re.sub.

def count_sub(pattern,text,repl=''):
    count=1
    while re.search(pattern,text):
        text=re.sub(pattern,repl+str(count),text,count=1)
        count+=1
    return text

输出:

count_sub(r'o', 'oh hello world')
# '1h hell2 w3rld'

count_sub(r'o', 'oh hello world','a')
# 'a1h hella2 wa3rld'

选择:

def count_sub1(pattern,text,repl=''):
    it=enumerate(re.finditer(pattern,text),1)
    count=1
    while count:
        count,_=next(it,(0,0))
        text=re.sub(pattern,repl+str(count),text,count=1)
    return text

输出:

count_sub1(r'o','oh hello world')
# '1h hell2 w3rld'

count_sub1(r'o','oh hello world','a')
# 'a1h hella2 wa3rld'
于 2020-04-07T19:04:32.370 回答