如何测试有效的 UUID/GUID? [英] How to test valid UUID/GUID?

查看:31
本文介绍了如何测试有效的 UUID/GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查变量是否包含有效的 UUID/GUID 标识符?

How to check if variable contains valid UUID/GUID identifier?

我目前只对验证类型 1 和 4 感兴趣,但这不应限制您的答案.

I'm currently interested only in validating types 1 and 4, but it should not be a limitation to your answers.

推荐答案

目前,UUID 是在 RFC4122 中指定的.一个经常被忽视的边缘情况是 NIL UUID,在此处注明.以下正则表达式将这一点考虑在内,并将返回 NIL UUID 的匹配项.有关仅接受非 NIL UUID 的 UUID,请参见下文.这两种解决方案都适用于版本 1 到 5(参见第三个块的第一个字符).

Currently, UUID's are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here. The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of the third block).

因此要验证 UUID...

Therefore to validate a UUID...

/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i

...确保您有一个规范格式的 UUID,它是版本 1 到版本 5,并且是符合 RFC4122 的相应变体.

...ensures you have a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.

注意:大括号 {} 不是规范的.它们是某些系统和用法的产物.

NOTE: Braces { and } are not canonical. They are an artifact of some systems and usages.

易于修改上述正则表达式以满足原始问题的要求.

Easy to modify the above regex to meet the requirements of the original question.

提示:正则表达式组/捕获

HINT: regex group/captures

为了避免匹配 NIL UUID:

To avoid matching NIL UUID:

/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

这篇关于如何测试有效的 UUID/GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆