When using a function in 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"))
How to get the match number inside custom_replace
?
i.e. 0, 1, 2 for the three "o" of the example input string.
NB: I don't want to use a global variable for this, because multiple such operations might happen in different threads etc.