当前位置:   article > 正文

java获取UUID与UUID的校验_java判断字符串是uuid类型

java判断字符串是uuid类型

背景:

我们在开发的过程中可能需要随机生成一个ID,例如数据库中的某个ID

有时候也要对其进行校验。

UUID:

UUID,是Universally Unique Identifier的缩写,UUID出现的目的,是为了让分布式系统可以不借助中心节点,就可以生成UUID来标识一些唯一的信息。

代码:

  1. import java.util.UUID;
  2. public class UUIDTest {
  3. public static void main(String[] args) {
  4. String uuid1 = "e65deb4c-a110-49c8-a4ef-6e69447968d6";
  5. String uuid2 = "ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb";
  6. String uuid3 = "e1f15f1d-6edb-4f70-8a05465se273eaf95a";
  7. System.out.println("check > " + uuid1 + " > " + isValidUUID(uuid1));
  8. System.out.println("check > " + uuid2 + " > " + isValidUUID(uuid2));
  9. System.out.println("check > " + uuid3 + " > " + isValidUUID(uuid3));
  10. System.out.println("build a uuid> " + getRandomUUID(null));
  11. System.out.println("build a uuid> " + getRandomUUID(null));
  12. System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));
  13. System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));
  14. }
  15. public static boolean isValidUUID(String uuid) {
  16. // UUID校验
  17. if (uuid == null) {
  18. System.out.println("uuid is null");
  19. }
  20. String regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
  21. if (uuid.matches(regex)) {
  22. return true;
  23. }
  24. return false;
  25. }
  26. public static UUID getRandomUUID(String str) {
  27. // 产生UUID
  28. if (str == null) {
  29. return UUID.randomUUID();
  30. } else {
  31. return UUID.nameUUIDFromBytes(str.getBytes());
  32. }
  33. }
  34. }

测试结果:

check > e65deb4c-a110-49c8-a4ef-6e69447968d6 > true
check > ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb > true
check > e1f15f1d-6edb-4f70-8a05465se273eaf95a > false
build a uuid>93ce6775-bc89-4849-8ae9-fb305c909700
build a uuid>7a61f2e0-903b-4904-b2bd-a075b19adb8c
build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae
build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/179746
推荐阅读
相关标签
  

闽ICP备14008679号