Search code examples
pythonregexpython-3.xregex-groupregex-greedy

How to store and remove a regex pattern at once?


I want to know if is possible to do this without checking for the regex pattern twice.

I am on python 3

pp = re.search(r'(.)(.+)\1(.+)', word)
word = re.sub(r'(.)(.+)\1(.+)', '', word)
salv = pp.groups()
word + = salv[0] + salv[0] + inverse(salv[1]) + salv[2]

There first I look for the matches, and then I remove the matches, but I am looking for the same regex patter twice. And I feel it can be done other way.

So what I want to do is:

Match a pattern, remove that pattern, and concat what I matched on a different way.


Solution

  • You can use the re.sub method with a function as the value for its repl argument.

    import re
    word = 'mmabacbc'
    print(re.sub(r'(.)(.+)\1(.+)', lambda m: m.group(1) * 2 + m.group(2).swapcase() + m.group(3), word))
    

    Output:

    mmaaBcbc
    

    Test it online with Rextester.