<pre><code>import re
e = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"
print ([e[i:j+1] for i in range(len(e)) for j in range(len(e)) if e[i:j+1].count('(') == e[i:j+1].count(')') != 0 and (e[i-1] == '(' or i == 0) and e[j] == ')'])
</code></pre>
<p>输出:</p>
<pre><code>["LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))", "Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')", 'Lower(UPPER([ProductName]+[ProductName]))', 'UPPER([ProductName]+[ProductName])']
</code></pre>
<p><em>展开的</em>版本:</p>
<pre><code>for i in range(len(e)):
for j in range(len(e)):
#Check for same number of opening/closing parenthesis
if e[i:j+1].count('(') == e[i:j+1].count(')') != 0:
#Check that (first char is preceded by an opening parenthesis OR that first char is the beginning of e) AND last char is a parenthesis
if (e[i-1] == '(' or i == 0) and e[j] == ')':
print (e[i:j+1])
</code></pre>
<p>输出:</p>
<pre><code>LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))
Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')
Lower(UPPER([ProductName]+[ProductName]))
UPPER([ProductName]+[ProductName])
</code></pre>