<p><strong>注意</strong>:<code>\(.*\)</code>匹配左边的第一个<code>(</code>,然后匹配到最后一个</em><code>)</code>的任何0+字符(如果未启用DOTALL修饰符,则不匹配换行符),并且不考虑正确嵌套的括号。</p>
<p><strong>要使用Python中的正则表达式正确删除嵌套括号,可以在<em>中使用简单的<a href="https://regex101.com/r/cQfh5r/2" rel="noreferrer">^{<cd4>}</a>(匹配a<code>(</code>,然后使用0+字符而不是<code>(</code>和<code>)</code>,然后使用a<code>)</code>),而使用<a href="https://docs.python.org/2/library/re.html#re.subn" rel="noreferrer">^{<cd9>}</a>的</em>块:</p>
<pre><code>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
</code></pre>
<p>基本上:去掉里面没有<code>(</code>和<code>)</code>的<code>(...)</code>,直到没有匹配。用法:</p>
<pre><code>print(remove_text_between_parens('stuff (inside (nested) brackets) (and (some(are)) here) here'))
# => stuff here
</code></pre>
<p>也可以使用非regex方式:</p>
<pre><code>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'
</code></pre>
<p>见<a href="https://ideone.com/2ZhSYQ" rel="noreferrer">another Python demo</a></p>