【发布时间】:2020-04-07 18:06:11
【问题描述】:
使用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”。
注意:我不想为此使用全局变量,因为多个此类操作可能发生在不同的线程等中。
【问题讨论】:
-
比赛号码是什么意思?
-
@Jan 我的意思是 0、1、2 表示示例输入字符串的三个“o”。
-
应该只使用
re.sub吗? -
@Ch3steR 我也愿意接受其他解决方案。