Skip to main content
 首页 » 编程设计

python之如何删除多层括号python中的文本

2025年05月04日16hnrainll

我有一个 python 字符串,我需要删除括号。标准的做法是使用text = re.sub(r'\([^)]*\)', '', text),所以括号内的内容会被去掉。

但是,我只是找到了一个看起来像 (Data with in (Boo) And good luck) 的字符串。使用我使用的正则表达式,它仍然会有 And good luck) 部分。我知道我可以扫描整个字符串并尝试保留 ( 和 ) 数量的计数器,当数字平衡时,索引 ( 和 ) 并删除中间的内容,但是有更好/更干净的方法吗?它不需要是正则表达式,无论它能做什么都很好,谢谢。

有人询问了预期的结果,所以这就是我所期待的:

Hi this is a test ( a b ( c d) e) 句子

替换后我希望它是 Hi this is a test sentence,而不是 Hi this is a test e) sentence

请您参考如下方法:

使用 re 模块(替换最里面的括号,直到没有更多替换可做):

import re 
 
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton' 
 
nb_rep = 1 
 
while (nb_rep): 
    (s, nb_rep) = re.subn(r'\([^()]*\)', '', s) 
 
print(s) 

随着regex module允许递归:

import regex 
 
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton' 
 
print(regex.sub(r'\([^()]*+(?:(?R)[^()]*)*+\)', '', s)) 

其中 (?R) 指的是整个模式本身。