Search code examples
pythonstringsubstringreversepython-re

py3 - reverse marked substrings within strings on all levels


I am trying to reverse all substrings that are in parentheses within a string. this post (Reverse marked substrings in a string) showed me how to do that (I am using the first answer), but I am having a problem with parentheses within parentheses. The code is currently not working with multiple layers of parentheses. For example the string 'ford (p(re)fe)ct', should return as 'ford efrepct', but is instead returning as 'ford er(pfe)ct'. (It should reverse the content of each parentheses in relation to its parent element).

here is my code:

def reverseInParentheses(iss):
    import re
    new = re.sub('\((.*?)\)', lambda m: m.group(1)[::-1], iss)

    print(new)

thanks!


Solution

  • One simple and naive approach to fix this: exclude opening parentheses within your matching group and just repeat until there are no more parentheses.

    import re
    
    def reverseInParentheses(iss):
        while '(' in iss:    
            iss = re.sub('\(([^\(]*?)\)', lambda m: m.group(1)[::-1], iss)
        return iss
    
    print(reverseInParentheses('ford (p(re)fe)ct'))
    # ford efrepct