我有一个解析xml
文件中的一行:
<ID>0b10-bd-59-ac-bac</ID>
我不知道ID
是在文本<>
和</>
。如果我想单独提取'ID
' ,我该如何处理'0b10-bd-59-ac-bac'
?re.search
需要你知道'ID'
,对吗?
你可以试试:
import re
s = " <ID>0b10-bd-59-ac-bac</ID> "
whole = re.findall("<.*?>.*</.*?>", s)[0]
inner = whole[whole.find(">") + 1: whole.rfind("<")]
outer = whole[whole.find("<") + 1: whole.find(">")]
print(whole)
print(inner)
print(outer)
输出:
<ID>0b10-bd-59-ac-bac</ID>
0b10-bd-59-ac-bac
ID
其中表达式<.*?>.*</.*?>
是模式:
<{anything but a <}>{anything}</{anything but a >}>
要解决您在评论中提供的其他模式,您可以尝试:
import re
strings = ['<ID>0b10-bd-59-ac-bac</ID>', '<Type ref="acc-63-5c-bl-5b"/>']
for s in strings:
outer = re.findall("(?<=<)[\w ]+", s)[0]
for inner in re.findall("[\w-]+", s):
if '-' in inner:
break
print("Outer", outer)
print("Inner", inner)
输出:
Outer ID
Inner 0b10-bd-59-ac-bac
Outer Type ref
Inner acc-63-5c-bl-5b
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句