Home > Software engineering >  Using Python, how can we check if a string is a valid UUID?
Using Python, how can we check if a string is a valid UUID?

Time:10-23

Given some string (e.g. 9c68ed68-1c80-4cf1-9ca9-477b5dd5fcb2), how can we verify that it is a valid UUID4 using Python? I have yet to see a clear answer (e.g. here and here) - it seems like there is always some sort of caveat these solutions. Is there an acceptable way to accomplish this? The nicest I've seen so far is in the second link I mentioned, which simply checks for its version inside a try/except block. For example:

def check_uuid4(test_uuid, version=4):
    try:
        return uuid.UUID(test_uuid).version == version
    except ValueError:
        return False

CodePudding user response:

To test wether provided string is UUID you can use regex, e.g. from these sites: Searching for UUIDs in text with regex or https://www.regextester.com/99148

Wrap this using regex module from python.

  • Related