How to find out the correspondence index in a regular expression function subn repl

Let's say I have the following line:

a<firstIndex>b<secondIndex>c<thirdIndex>

And I want to replace all events with a r'<\w+Index>'number corresponding to a match number. Therefore, given the above line, the return value will be:

a1b2c3

I know that there are many ways to do this in the code (for example, by writing a class with a counter that keeps track of the correspondence index), but I am wondering if this is possible only through standard library functions.

I suppose, more specifically, I am wondering if you can get this information from the object MatchObjectpassed to the replfunction used in subn.

+4
source share
1 answer

re.sub. re.sub ( re.subn) , str. (, ) repl, .

match , , , callable, , . :

class Replacer:  # On Py2, use class Replacer(object): to explicitly use new style classes
    def __init__(self):
        self.matchcnt = 0
    def __call__(self, matchobj):
        self.matchcnt += 1
        return matchobj.group(0) + str(self.matchcnt)

re.sub/re.subn, Replacer() repl; matchcnt, __call__, ; , , , . sub, , sub .

+5

Source: https://habr.com/ru/post/1610509/