Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to judge a string is UUID type? [duplicate]

Tags:

java

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?

like image 666
Elton Wang Avatar asked Nov 18 '13 05:11

Elton Wang


People also ask

How do you check if a string is a UUID?

So to check if a string is valid UUID we can use this regular expression, // Regular expression to check if string is a valid UUID const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi; This matches all the valid UUID since it checks for the above test cases.

How do I know my UUID type?

Use the . match() method to check whether String is UUID.

Is UUID type string?

UUIDs support input of case-insensitive string literal formats, as specified by RFC 4122. In general, a UUID is written as a sequence of hexadecimal digits, in several groups optionally separated by hyphens, for a total of 32 digits representing 128 bits.

How do you check if a string is a valid UUID in Python?

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8 , 9 , A , or B . Before performing the regex, I might add a quick simple IF() to test if the length of the string is 32 or 36 characters long. If not, it's not a UUID hex string.


2 Answers

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  } 
like image 181
Saša Šijak Avatar answered Oct 22 '22 06:10

Saša Šijak


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}‌​\}?$ 
like image 43
Imran Avatar answered Oct 22 '22 07:10

Imran