Skip to main content
 首页 » 编程设计

python之如何使用 re.compile 和 re.findall 删除括号内的文本

2024年11月24日7jillzhang

我想删除括号之间的文字(包括括号)。此文本存储在列表中。我还想存储输出文本(在新列表中没有括号)。

我尝试使用:

es = ["49,331,076","23,136,275","139,500 (est.)","124,000","522 (ranked 23 of 137)"] 
length=len(es) 
regex = re.compile(".*?\((.*?)\)") 
for x in range(length): 
    listy.append(re.findall(regex, es[p])) 
    p=p+1 

但是,这将返回括号之间的文本。

预期结果:

"[49,331,076, 23,136,275, 139,500, 124,000, 522]" 

我得到的结果:

"[], [], [est.], [u'ranked 18 of 137']" 

请您参考如下方法:

您可以使用 re.sub用\([^()]*\)图案:

import re 
es = ["49,331,076","23,136,275","139,500 (est.)","124,000","522 (ranked 23 of 137)"] 
regex = re.compile(r"\([^()]*\)") 
listy = [] 
for x in es: 
    listy.append(regex.sub('', x).strip()) 
# Or, instead of the two lines above use a list comprehension: 
# listy = [regex.sub('', x).strip() for x in es] 
print(listy) # => ['49,331,076', '23,136,275', '139,500', '124,000', '522'] 

参见 Python demo

请注意,使用 for x in es: 更容易遍历列表项,无需获取其长度,然后使用计数器跟踪当前项目。使用列表理解更像 Pythonic,[regex.sub('', x).strip() for x in es] .

\([^()]*\)模式匹配( ,然后是除 ( 以外的任何 0+ 个字符和 )然后是 ) .如果有可以(在两者之间,使用 \(.*?\)或 \([^)]*\) .