How to remove all text between outer brackets in a string?

When I have a line like this:

s1 = 'stuff(remove_me)'

I can easily remove parentheses and text inside using

# returns 'stuff'
res1 = re.sub(r'\([^)]*\)', '', s1)

as described here .

But sometimes I come across these nested expressions:

s2 = 'stuff(remove(me))'

When I run the command from above, I end up with

'stuff)'

I also tried:

re.sub('\(.*?\)', '', s2)

which gives me the same result.

How can I remove everything from external parentheses, including the parentheses themselves, so that I also get 'stuff'(which should work for arbitrarily complex expressions)?

+4
source share
5 answers

re , . , , :

>>> re.sub(r'\(.*\)', '', 'stuff(remove(me))')
'stuff'
+2

: \(.*\) ( , 0+ ( , DOTALL ) ) .

Python, \([^()]*\) ( (, 0+, ( ), a )) while, re.subn:

def remove_text_between_parens(text):
    n = 1  # run at least once
    while n:
        text, n = re.subn(r'\([^()]*\)', '', text)  # remove non-nested/flat balanced parts
    return text

Bascially: (...) ( ) , . :

print(remove_text_between_parens('stuff (inside (nested) brackets) (and (some(are)) here) here'))
# => stuff   here

:

def removeNestedParentheses(s):
    ret = ''
    skip = 0
    for i in s:
        if i == '(':
            skip += 1
        elif i == ')'and skip > 0:
            skip -= 1
        elif skip == 0:
            ret += i
    return ret

x = removeNestedParentheses('stuff (inside (nested) brackets) (and (some(are)) here) here')
print(x)              
# => 'stuff   here'

. Python

+5

, , , :

\((?:[^)(]|\([^)(]*\))*\)
  • [^)(] , ( ).
  • |\([^)(]*\) ( ) )( .
  • (?:... )* ( )

regex101

, [^)(] +, , .
, . , max 2 :

\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\)

regex101

+2

, , :

re.sub(r'\(.*\)', '', s2)
+1

https://regex101.com/r/kQ2jS3/1

'(\(.*\))'

furthest .

next.

0

All Articles