-2

I wanted to understand this regular expression in Python: \([^\(\)]*\

The full code is below. It reverses text inside of parentheses.

import re

def reverseParentheses(s):
    s_new = s
    count = 0
    while True:
        mat = re.findall(r'\([^\(\)]*\)',s_new)
        if not mat:
            break
        for i in mat:
            temp = re.sub(r'\(|\)', '', i)
            s_new = re.sub(re.escape(i), temp[::-1], s_new)
    return(s_new)

2 Answers2

2

Lets break it:

\(   \)
Start with ( and ends with )

[]*
^ A char that is part of the char-group any number of times.

^
^ Not one of the following chars

\(\)
^ ( or ) - because they appear inside the char-group

So basically if we take this:

[^\(\)]*
^ Any char that is not ( and not ), any number of times.

And if we combine all of the above we get something like:

A string that starts with ( followed by any char that is not ( and not ) and ends with )

Dekel
  • 53,749
  • 8
  • 76
  • 105
0

\ usually is associate with d, or some other character that represents a decimal or some other type of literal. In this case it just means the literal '('

r'\(' >>> r(

[] is a bracket that represents any set of strings (i.e. [abc] would represent anything from either a,b, or c

^ something anchored to beginning of the string set (i.e. ^a would look for no a in string) [^abc] looks for not a or b or c or in this case not the literal ( and not the literal )

  • represents that the pattern is matched either 0,1,2,3... or more times

'\)' >>> )

an example: r( ) is the minimum

r(())))) would fail

r(((((() would fail

r( ) ) would fail because as you can see [^()] is anchored

r( LITERALLY ANYTHING EXCEPT '(' or ')' )