Python and regex, keep text inside a pattern and remove the outside

Viewed 52

I have text that looks like the following:

my_string = "a + (foo(b)*foo(c))

And I am trying to remove the parentheses that start with C. So the desired output would look like

"a + (b*c)

I found the following to find all patterns inside the string, but not to remove in place.

re.findall(r'foo\((.*?)\)', my_string)
1 Answers
        my_string = "a + (foo(b)*foo(c))"

        # \w+ to remove foo, that is followed by ( 
        # \( , \) to remove () around 'b' and 'c' 
    
        re.sub(r'\w+\((\w)\)',r'\1', my_string)
        
        a + (b*c)
Related