简体   繁体   English

使用 Python,我们如何检查字符串是否是有效的 UUID?

[英]Using Python, how can we check if a string is a valid UUID?

Given some string (eg 9c68ed68-1c80-4cf1-9ca9-477b5dd5fcb2 ), how can we verify that it is a valid UUID4 using Python?给定一些字符串(例如9c68ed68-1c80-4cf1-9ca9-477b5dd5fcb2 ),我们如何使用 Python 验证它是有效的 UUID4? I have yet to see a clear answer (eg 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.迄今为止我所看到的最好的是在我提到的第二个链接中,它只是在 try/except 块中检查其版本。 For example:例如:

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

To test wether provided string is UUID you can use regex, eg from these sites: Searching for UUIDs in text with regex or https://www.regextester.com/99148要测试提供的字符串是否为 UUID,您可以使用正则表达式,例如来自这些站点: 使用正则表达式https://www.regextester.com/99148 在文本中搜索 UUID

Wrap this using regex module from python.使用来自 python 的 regex 模块包装它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM