What is the correct regex for matching values generated by uuid.uuid4().hex?

后端 未结 4 1021
一生所求
一生所求 2021-02-05 00:38

How do I validate that a value is equal to the UUID4 generated by this code?

uuid.uuid4().hex

Should it be some regular expression? The values

4条回答
  •  暖寄归人
    2021-02-05 01:13

    As far as I know, Martijn's answer is not 100% correct. A UUID-4 has five groups of hexadecimal characters, the first has 8 chars, the second 4 chars, the third 4 chars, the fourth 4 chars, the fifth 12 chars.

    However to make it a valid UUID4 the third group (the one in the middle) must start with a 4:

    00000000-0000-4000-0000-000000000000
                  ^
    

    And the fourth group must start with 8, 9, a or b.

    00000000-0000-4000-a000-000000000000
                  ^    ^
    

    So you have to change Martijn's regex to:

    import re
    uuid4hex = re.compile('[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}\Z', re.I)
    

    Hope this helps!

提交回复
热议问题