Python - 基于未知文本和已知字符获取子字符串(解析 xml 的结果)

胡椒小姐

我有一个解析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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章