Search code examples
pythonregexsubstitutionparentheses

Error in substituting '(' with regex in Python


Hi have the following string:

s = r'aaa (bbb (ccc)) ddd'

and I would like to find and replace the innermost nested parentheses with {}. Wanted output:

s = r'aaa (bbb {ccc}) ddd'

Let's start with the nested (. I use the following regex in order to find nested parentheses, which works pretty good:

match = re.search(r'\([^\)]+(\()', s)
print(match.group(1))
(

Then I try to make the substitution:

re.sub(match.group(1), r'\{', s)

but I get the following error:

error: missing ), unterminated subpattern at position 0

I really don't understand what's wrong.


Solution

  • You can use

    import re
    s = r'aaa (bbb (ccc)) ddd'
    print( re.sub(r'\(([^()]*)\)', r'{\1}', s) )
    # => aaa (bbb {ccc}) ddd
    

    See the Python demo.

    Details:

    • \( - a ( char
    • ([^()]*) - Group 1 (\1): any zero or more chars other than ( and )
    • \) - a ) char.

    The replacement is a Group 1 value wrapped with curly braces.