我有以下形式的字符串:
}# => 2[1 HMDB00001 ,2 HMDB00002]
}# => 5[1 HMDB00001 ,2 HMDB00002, 3 HMDB00003 ,4 HMDB00004,5 HMDB00005]
}# => 1[1 HMDB00001]
<。>在.txt文件中。我试图使用正则表达式的re.search()在python列表中解析它们,但到目前为止还不成功。您可以猜测列表应包含以下元素elements = ["1 HMDB00001", "2 HMDB00002", "3 HMDB00003"]
。列表彼此独立。因此,当仅解析一行时,可以考虑(eg. }# => 2[1 HMDB00001 ,2 HMDB00002])
。
答案 0 :(得分:2)
(?<=[\[,])\s*(\d+ HMDB0+\d+)
请改用re.findall
。参见演示。
https://regex101.com/r/eS7gD7/19#python
import re
p = re.compile(r'(?<=[\[,])\s*(\d+ HMDB0+\d+)', re.IGNORECASE | re.MULTILINE)
test_str = "}# => 2[1 HMDB00001 ,2 HMDB00002]\n}# => 5[1 HMDB00001 ,2 HMDB00002, 3 HMDB00003 ,4 HMDB00004,5 HMDB00005]\n}# => 1[1 HMDB00001]"
re.findall(p, test_str)
答案 1 :(得分:0)
这似乎有效,但鉴于你的问题很难确定。您可以从所得到的答案中拼凑出一个解决方案。
import re
strings = [
'}# => 2[1 HMDB00001 ,2 HMDB00002]',
'}# => 5[1 HMDB00001 ,2 HMDB00002, 3 HMDB00003 ,4 HMDB00004,5 HMDB00005]',
'}# => 1[1 HMDB00001]',
]
for s in strings:
mat = re.search(r'\[(.*)\]', s)
elements = map(str.strip, mat.group(1).split(','))
print elements
哪个输出:
['1 HMDB00001', '2 HMDB00002']
['1 HMDB00001', '2 HMDB00002', '3 HMDB00003', '4 HMDB00004', '5 HMDB00005']
['1 HMDB00001']
答案 2 :(得分:0)
假设您的模式完全符合:一个数字,一个空格,HMDB
,5个数字,按此顺序排列。
结果存储在每行的dict中。
import re
matches = {}
with open('my_text_file.txt', 'r') as f:
for num, line in enumerate(f):
matches.update({num: re.findall(r'\d\sHMDB\d{5}', line)})
print(matches)
如果HMDB
可能不同,您可以使用r'\d\s[a-zA-Z]{4}\d{5}'
。