1. Overview
1.概述
In this tutorial, we’re going to have a look at some ways of validating UUID (Universally Unique Identifier) strings in Java.
在本教程中,我们将看看在Java中验证UUID(通用唯一标识符)字符串的一些方法。
We’ll go through one of the UUID class methods, and then we’ll use regular expressions.
我们将通过UUID类方法中的一个,然后我们将使用正则表达式。
2. Using UUID.fromString()
2.使用UUID.fromString()
One of the quickest ways of checking if a String is a UUID is by trying to map it using the static method fromString belonging to the UUID class. Let’s try it out:
检查一个String是否是UID的最快方法之一是尝试使用属于UID类的静态方法fromString来映射它。让我们来试试吧。
@Test
public void whenValidUUIDStringIsValidated_thenValidationSucceeds() {
String validUUID = "26929514-237c-11ed-861d-0242ac120002";
Assertions.assertEquals(UUID.fromString(validUUID).toString(), validUUID);
String invalidUUID = "invalid-uuid";
Assertions.assertThrows(IllegalArgumentException.class, () -> UUID.fromString(invalidUUID));
}
In the above code snippet, we can see that in case the string we’re trying to validate doesn’t represent a UUID, then an IllegalArgumentException will be thrown. However, the method fromString will return `00000001-0001-0001-0001-000000000001` for strings such as `1-1-1-1-1`. So we have included the string comparison to take care of this case.
在上面的代码片段中,我们可以看到,如果我们试图验证的字符串不代表UUID,那么就会抛出IllegalArgumentException。然而,方法fromString将返回 “00000001-0001-0001-000000000001 “的字符串,如 “1-1-1-1″。所以我们加入了字符串比较来处理这种情况。
Some might argue that using exceptions is not a good practice for flow control, so we’re going to see a different way of achieving the same result.
有些人可能会说,使用异常并不是流控制的好做法,所以我们将看到一种不同的方式来实现同样的结果。
3. Using Regular Expressions
3.使用正则表达式
Another way of validating a UUID is to use a regular expression that will match exactly the format.
另一种验证UUID的方法是使用正则表达式,它将与格式完全匹配。
Firstly, we need to define a Pattern that will be used to match the string.
首先,我们需要定义一个Pattern,它将用于匹配字符串。
Pattern UUID_REGEX =
Pattern.compile("^[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}$");
Then, we can use this pattern to try matching it to a string in order to validate whether or not it is a UUID:
然后,我们可以使用这个模式来尝试将它与一个字符串相匹配,以验证它是否是一个UUID。
@Test
public void whenUUIDIsValidatedUsingRegex_thenValidationSucceeds() {
Pattern UUID_REGEX =
Pattern.compile("^[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}$");
Assertions.assertTrue(UUID_REGEX.matcher("26929514-237c-11ed-861d-0242ac120002").matches());
Assertions.assertFalse(UUID_REGEX.matcher("invalid-uuid").matches());
}
4. Conclusion
4.总结
In this article, we’ve learned how to validate a UUID string by using regular expressions or by taking advantage of the static method of the UUID class.
在这篇文章中,我们已经学会了如何通过使用正则表达式或利用UUID类的静态方法来验证UUID字符串。
As always, the code for these examples is available over on GitHub.
像往常一样,这些例子的代码可以在GitHub上找到over。