I generate UUIDs, and valid them against a Regex in my code; I just ran into problems that confused me
Here is the code that generates UUIDs (in a mongodb context)
import java.util.UUID; ... ... Document setOnInsert = new Document(Params.sender, UUID.randomUUID()) .append(Params.userDevice, userDevice) .append(Params.hostId,""); This is the code of validating an UUID; I had copied the Regex from this post
static final Pattern UUID = Pattern.compile("([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})"); public static boolean isUUID(String uuid){ if(uuid == null){ return false; }else{ return UUID.matcher(uuid).matches(); } } and below are the 2 UUIDs that I have problems with
aa4aaa2c-c6ca-d5f5-b8b2-0b5c78ee2cb7 b24dd64c-de6b-5bf6-6283-aa2167cc93a7 These two UUIDs had been generated by the code mentioned above; the validating method (isUUID()) judged them as invalid in my latest debug; yet I posted these UUIDs to an online validator , and it says ok
This is my system information
wjz@bj:~$ java -version java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) wjz@bj:~$ wjz@bj:~$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 16.04.1 LTS Release: 16.04 Codename: xenial wjz@bj:~$ Some background: I had been working on jdk 1.8.0_111; these UUIDs had been generated then, and had no problems. then I upgraded to 1.8.0_121 today, and run into this problem...
So my question is: Whether the above mentioned UUIDs are correct or wrong? who to believe, the generator or the validation
UUID.fromString()[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}. In the first one you've got a "d" where you should have 1-5; in the second one you've got 6 where you should have 8-b.hexOctet(which is two hex digits each). You are restricting it more than the specification does. Trust the built-in generator, distrust the "found somewhere on the internet" validator.