How to judge a string is UUID type?

Java

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 
}

Solution 2 - Java

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

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}‌​\}?$

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElton WangView Question on Stackoverflow
Solution 1 - JavaSaša ŠijakView Answer on Stackoverflow
Solution 2 - JavaImranView Answer on Stackoverflow