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

后端 未结 4 1019
一生所求
一生所求 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:21

    To be more specific. This is the most precise regex for catching uuid4 both with and without dash, and that follows all the rules of UUID4:

    [a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}
    

    You can make sure it also catches capital letters with ignore case. In my example with re.I. (uuid's do not have capital letters in it's output, but in input it does not fail, just ignores it. Meaning that in a UUID "f" and "F" is the same)

    I created a validater to catch them looking like this:

    def valid_uuid(uuid):
        regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
        match = regex.match(uuid)
        return bool(match)
    

    Then you can do:

    if valid_uuid(my_uuid):
        #Do stuff with valid my_uuid
    

    With ^ in the start and \Z in the end I also make sure there is nothing else in the string. This makes sure that "3fc3d0e9-1efb-4eef-ace6-d9d59b62fec5" return true, but "3fc3d0e9-1efb-4eef-ace6-d9d59b62fec5+19187" return false.

    Update - the python way below is not foolproof - see comments:

    There are other ways to validate a UUID. In python do:

    from uuid import UUID
    try:
        UUID(my_uuid)
        #my_uuid is valid and you can use it
    except ValueError:
        #do what you need when my_uuid is not a uuid
    

提交回复
热议问题