擅长:python、mysql、java
<p>此解决方案适用于任意嵌套的括号,正则表达式不能(<code>s</code>是原始字符串):</p>
<pre><code>from pyparsing import nestedExpr
def lst_to_parens(elt):
if isinstance(elt,list):
return '(' + ' '.join(lst_to_parens(e) for e in elt) + ')'
else:
return elt
split = nestedExpr('(',')').parseString('(' + s + ')').asList()
split_lists = [elt for elt in split[0] if isinstance(elt,list)]
print ([lst_to_parens(elt) for elt in split_lists])
</code></pre>
<p>输出:</p>
<pre><code>['(some text)', '((other text) and (some more text))', '(still more text)']
</code></pre>
<p>对于OP的真实测试用例:</p>
<pre><code>s = "(substringof('needle',name)) or ((role eq 'needle') and (substringof('needle',email))) or (job eq 'needle') or (office eq 'needle')"
</code></pre>
<p>输出:</p>
<pre><code>["(substringof ('needle' ,name))", "((role eq 'needle') and (substringof ('needle' ,email)))", "(job eq 'needle')", "(office eq 'needle')"]
</code></pre>