我有一个python字符串,我需要删除括号。标准方法是使用text = re.sub(r'\([^)]*\)', '', text)
,因此括号内的内容将被删除。如何删除多层圆括号中的文本python
但是,我刚刚发现一个看起来像(Data with in (Boo) And good luck)
的字符串。随着我使用的正则表达式,它仍然有And good luck)
部分。我知道我可以扫描整个字符串并尝试保留一个数字为(
和)
的计数器,并且当数字平衡时,索引(
和)
的位置并删除中间的内容,但是会有更好还是更清晰的方式为了做到这一点?它不需要是正则表达式,无论它会工作是多么伟大,谢谢。
有人问了那么这里预期的结果是什么,我期待:
Hi this is a test (a b (c d) e) sentence
更换后我希望它是Hi this is a test sentence
,而不是Hi this is a test e) sentence
这是不可能的re模块做到这一点,但你可以用正则表达式模块,允许递归做到这一点。 https://pypi.python.org/pypi/regex –
在最坏的情况下,如果你建立一个模式来匹配最内层的括号'\([^()] * \),那么你可以用re模块来完成它,如果你循环替换,直到没有任何东西可以替换。但它不是一个非常优雅的方式,因为你需要多次解析字符串。 –
你对非正则表达式解决方案开放吗? – Dan