Java 如何判断一个字符串是UUID类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20041051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:35:50  来源:igfitidea点击:

How to judge a string is UUID type?

java

提问by Elton Wang

In my project, I use UUID.fromString()to convert string to UUID, but if the string is not UUIDtype, it will throw exception, so how can I validate this string?

在我的项目中,我使用UUID.fromString()将字符串转换为UUID,但是如果字符串不是UUID类型,它会抛出exception,那么我该如何验证这个字符串呢?

采纳答案by Imran

You should use regex to verify it e.g.:

您应该使用正则表达式来验证它,例如:

/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/

test it with e.g.g 01234567-9ABC-DEF0-1234-56789ABCDEF0

用鸡蛋测试一下 01234567-9ABC-DEF0-1234-56789ABCDEF0

or with brackets

或带括号

/^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}??\}?$/

回答by Sa?a ?ijak

Handle the exception and do something in that case. For example :

处理异常并在这种情况下做一些事情。例如 :

try{
    UUID uuid = UUID.fromString(someUUID);
    //do something
} catch (IllegalArgumentException exception){
    //handle the case where string is not valid UUID 
}