python - 如何删除字符串中外括号之间的所有文本?

标签 python regex parentheses

当我有这样的字符串时:

s1 = 'stuff(remove_me)'

我可以很容易地删除括号和使用中的文本

# returns 'stuff'
res1 = re.sub(r'\([^)]*\)', '', s1)

解释为 here .

但我有时会遇到这样的嵌套表达式:

s2 = 'stuff(remove(me))'

当我从上面运行命令时,我最终得到了

'stuff)'

我也试过:

re.sub('\(.*?\)', '', s2)

这给了我相同的输出。

我怎样才能删除外括号内的所有内容 - 包括括号本身 - 以便我也以 'stuff' (它应该适用于任意复杂的表达式)结束?

最佳答案

注意:\(.*\) 匹配左边的第一个 (,然后匹配任何 0+ 个字符(a 除外换行符(如果未启用 DOTALL 修饰符)直到 last ),并且不考虑正确嵌套的括号。

要在 Python 中使用正则表达式正确删除嵌套的括号,您可以使用简单的 \([^()]*\) (匹配 (,然后是 () 以外的 0+ 个字符,然后是 ))在 < em>while 阻止使用 re.subn :

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

基本上:删除里面没有()(...),直到找不到匹配项。用法:

print(remove_text_between_parens('stuff (inside (nested) brackets) (and (some(are)) here) here'))
# => stuff   here

非正则表达式的方式也是可能的:

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'

参见 another Python demo

关于python - 如何删除字符串中外括号之间的所有文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528373/

相关文章:

Python 2.6 字体/颜色更改 + 错误窗口

python - 子进程不会实时显示来自 tcpdump 的数据。它显示暂停约 10-20 秒

regex - Google Big Query 中 REGEXP_MATCH 的奇怪行为

javascript - 如何在 javascript 中使用正则表达式替换来查找字符串中最长的匹配字符序列?

python - django doctests 没有运行

python - 期间停止 Python 中的多行正则表达式替代?

java - 查找文本直到行正则表达式的末尾

regex - 删除最外面的括号

python - Pandas - 获取 pandas 数据框列括号内的值

c - 在 C 中始终将定义括在括号中是否有充分的理由?