如何删除字符串中外括号之间的所有文本? [英] How to remove all text between the outer parentheses in a string?
问题描述
当我有这样的字符串时:
s1 = 'stuff(remove_me)'
我可以使用 using 轻松删除括号和文本
# 返回东西"res1 = re.sub(r'\([^)]*\)', '', s1)
如此处所述.
但我有时会遇到这样的嵌套表达式:
s2 = 'stuff(remove(me))'
当我从上面运行命令时,我得到了
'东西)'
我也试过:
re.sub('\(.*?\)', '', s2)
这给了我相同的输出.
如何删除外括号内的所有内容 - 包括括号本身 - 以便我最终得到 'stuff'
(它应该适用于任意复杂的表达式)?
re
匹配是急切的,因此他们尝试匹配尽可能多的文本,对于您提到的简单测试用例,只需使用正则表达式运行:
When I have a string like this:
s1 = 'stuff(remove_me)'
I can easily remove the parentheses and the text within using
# returns 'stuff'
res1 = re.sub(r'\([^)]*\)', '', s1)
as explained here.
But I sometimes encounter nested expressions like this:
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 output.
How can I remove everything within the outer parentheses - including the parentheses themselves - so that I also end up with 'stuff'
(which should work for arbitrarily complex expressions)?
re
matches are eager so they try to match as much text as possible, for the simple test case you mention just let the regex run:
>>> re.sub(r'\(.*\)', '', 'stuff(remove(me))')
'stuff'
这篇关于如何删除字符串中外括号之间的所有文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!