Skip to main content
 首页 » 编程设计

python之提取最后一次出现的大括号之间的文本

2025年05月04日9EasonJim

我有这样的字符串,

Protein XVZ [Human] 
Protein ABC [Mouse] 
Protein CDY [Chicken [type1]] 
Protein BBC [type 2] [Bacteria] 

输出应该是,

Human 
Mouse 
Chicken [type1] 
Bacteria 

因此,我想要最后一对大括号内的所有内容。必须像上一个示例一样忽略该对之前的大括号。有没有一种有效的方法可以在 Python 中执行此操作?预先感谢您的帮助。

请您参考如下方法:

这个怎么样:

import re 
list = ["Protein XVZ [Human]","Protein ABC [Mouse]","go UDP[3] glucosamine N-acyltransferase [virus1]","Protein CDY [Chicken [type1]]","Protein BBC [type 2] [Bacteria] [cat] [mat]","gi p19-gag protein [2] [Human T-lymphotropic virus 2]"] 
pattern = re.compile("\[(.*?)\]$") 
for string in list: 
    match = re.search(pattern,string) 
    lastBracket = re.split("\].*\[",match.group(1))[-1] 
    print lastBracket