Python regex太贪婪,缺少XML中的第一个出现

2024-09-30 04:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python正则表达式:

xml_parse = re.search(r'^.+?<Hit_accession>(\w+?)</Hit_accession>.+?<Hsp_qseq>(\w+?)</Hsp_qseq>\s+?<Hsp_hseq>(\w+?)</Hsp_hseq>\s+?<Hsp_midline>(.+?)</Hsp_midline>',string,flags=re.DOTALL)

对于以下文本:

^{pr2}$

返回的组是:
(1) 理想组1
(2) 非期望组2
(3) 非期望组3
(4) 非期望组#4

为什么会这样?因为我得到了想要的组#1并使用了非贪心?带着旗子=雷多尔,我希望它不会跳过我想要的第2-4组。在

提前谢谢。在


更新:

最后使用xml.etree.ElementTree具体如下:

tree = xml.etree.ElementTree.fromstring(string)
iteration = tree.find("BlastOutput_iterations/Iteration")
hits = iteration.findall("Iteration_hits/Hit")
topHit = hits[0]
accessionNCBI = topHit.findtext("Hit_accession")  

发现以下链接对NCBI BLAST特定的XML解析示例很有用: http://www.dalkescientific.com/writings/NBN/elementtree.html


Tags: retreestringxmletreehitselementtreehit
1条回答
网友
1楼 · 发布于 2024-09-30 04:32:19

Hmmm、XML和Regex。看起来很有趣。在

不如使用内置的pythonxml库,比如libxml2或ElementTree?在

from xml.etree.ElementTree import ElementTree
doc = ElementTree(file='myfile.xml')

for e in doc.findall('/Hit_accession'):
    print e.get('Hsp_qseq').text

说真的,你会省去很多麻烦。Regex不是用于XML解析的。在

相关问题 更多 >

    热门问题