1

在要处理的输入 XML 中,我有一个 URN UUID 作为 fileIdentifier:

urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b

我需要检查此 UUID 是否有效,但该vendor:processor:部分使标准模块引发错误:

# same UUID in different flavors
x = "0269803d50c446b09f5060ef7fe3e22b"
y = "urn:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"
z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"

# testing different ways
uuid.UUID(x)
>>> UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b')  # yipee
uuid.UUID(y)
>>> UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b')  # yipee 2
uuid.UUID(z)
>>> Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\uuid.py", line 140, in __init__
        raise ValueError('badly formed hexadecimal UUID string')
      ValueError: badly formed hexadecimal UUID string

如何指定它vendor:processor:是 UUID 命名空间的一部分(不确定这个术语是否正确)?

环境:Python 3.6.4 64 位 - Win10

4

1 回答 1

2

根据手册,UUID URN应该符合 RFC4122。现在,据我所知,RFC不支持此类“前缀”,因此我认为您将不得不手动解析该 URN。示例代码:

import uuid

# Returns a tuple (<uuid>, <prefix>)
def urn_uuid_decode(urn_str):
    parts = urn_str.split(":")

    # Already supported format
    if len(parts) < 4:
        return uuid.UUID(urn_str), None


    return uuid.UUID("%s:%s:%s" % (parts[0], parts[-2], parts[-1])), ":".join(parts[1:-2])

# same UUID in different flavors
x = "0269803d50c446b09f5060ef7fe3e22b"
y = "urn:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"
z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"

print(urn_uuid_decode(x))
print(urn_uuid_decode(y))
print(urn_uuid_decode(z))

输出:

(UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), None)
(UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), None)
(UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), 'vendor:processor')

希望能帮助到你

于 2018-03-20T11:03:19.003 回答