Search code examples
pythonregexpython-re

Can I reference a number in Regex capture group, manipulate it, and then replace it back?


For example I have a string like this:

Hello I am 'v0' to be added

I want to change it to:

Hello I am 'v1' to be added

So I am trying to substitute 'v0' using below:

re.sub(r'(\W)v\d+(\W)', r'\1vnew\2', string)

And then now I get:

Hello I am 'vnew' to be added

But then I don't know how to manipulate numbers here.

Apparently re.sub(r'(\W)v(\d+)(\W)', rf'\1v{int(\2)+1}\3', string) does not work because SyntaxError: f-string expression part cannot include a backslash.

Any idea except doing these in separate steps, i.e. capture the number, add it and change it to a string before doing re.sub()?


Solution

  • You can increment the matched number by using a lambda function to replace the value. Note that you can simplify the code also by using lookarounds to avoid matching anything other than the digits after the v:

    import re
    
    s = 'Hello I am \'v0\' to be added'
    s = re.sub(r'(?<=\Wv)\d+(?=\W)', lambda m: str(int(m.group(0)) + 1), s)
    print(s)
    

    Output

    Hello I am 'v1' to be added