Quantcast
Viewing all articles
Browse latest Browse all 3

Python regex to find nested parentheses outside double quotes

I have an input string which contains parenthesis inside and outside double quotes.These parentheses can be nested. I want to strip off strings with parentheses present only outside of double quotes.

I tried this regex r'\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\)'This fetches everything that is enclosed within round brackets no matter inside or outside double quotes.

    import re    input_string = '''"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes))'''    result = re.sub(r'\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\)','', input_string)    print result

The actual output I am getting is:

'"Hello World "  anything outside round brackets should remain as is'

I expect the output to be:

'"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is'

Viewing all articles
Browse latest Browse all 3

Trending Articles