Home > Net >  Retain intermediate string using regex
Retain intermediate string using regex

Time:10-07

I want to append a substring to a string pattern at all occurrences in multiple python code files. However the original string follows a pattern and is not an exact same string each time. Below are some examples of the variation:

Original Code:  a.b();
Want Code:      a.b().c();
Original Code:  a.b(param1=1);
Want Code:      a.b(param1=1, param2=2).c();
Original Code:  a.b(param1=1, param2=2);
Want Code:      a.b(param1=1, param2=2).c();

I am not really concerned about parameters passed in function b. I simply need to append invocation of c() every time a.b() is invoked.

I am using the regex 'a.b(.*?)' to detect the appropriate original code. I tried using the following solution regexes: a.b($1).c() or a.b(\1).c() but to no avail.

CodePudding user response:

You can use

a\.b\([^()]*\)(?=;)
  • a\.b Match literally and escape the dot
  • \([^()]*\) Match from an opening parenthesis till closing parenthesis using a negated character class
  • (?=;) Positive lookahead, assert a ; to the right

Regex demo | Python demo

And replace with the full match \g<0> followed by .c()

\g<0>.c()

For example:

import re

regex = r"a\.b\([^()]*\)(?=;)"

s = ("a.b();\n"
    "a.b(param1=1);\n"
    "a.b(param1=1, param2=2);")

result = re.sub(regex, r"\g<0>.c()", s)

if result:
    print (result)

Output

a.b().c();
a.b(param1=1).c();
a.b(param1=1, param2=2).c();

CodePudding user response:

How about this:

Pattern: (a\.b\(.*?\))

Replacement: \1.c()

Result:

a.b(param1=1).c();
a.b(param1=1, param2=2).c();
a.b().c();

https://regex101.com/r/VwxWR3/1/

  • Related