This is an example of function that validates UUID strings without hyphens. It's faster because it doesn't use regexp or buffering. A UUID without hyphens is just a string of 32 hexadecimal chars.
public class Example1 {
/**
* Validate UUID without hyphens.
*
* @param uuid a uuid string
* @return true if valid
*/
public static boolean isValid(String uuid) {
if (uuid == null || uuid.length() != 32) {
return false;
}
final char[] chars = uuid.toCharArray();
for (int i = 0; i < chars.length; i++) {
final int c = chars[i];
if (!((c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x66) || (c >= 0x41 && c <= 0x46))) {
// ASCII codes: 0-9, a-f, A-F
return false;
}
}
return true;
}
public static void main(String[] args) {
String uuid = "005056963AB75FD48BDC59C100314C40";
if(isValid(uuid)) {
// do something
}
}
}
You can also use UuidValidator.isValid()
from the library uuid-creator
. It validates UUID strings with or without hyphens. This is another example:
import com.github.f4b6a3.uuid.util.UuidValidator;
public class Example2 {
public static void main(String[] args) {
String uuid = "005056963AB75FD48BDC59C100314C40";
if(UuidValidator.isValid(uuid)) {
// do something
}
}
}
But if you just want to convert a string into a UUID, you can use UuidCreator.fromString()
. This function also validates the input.
import java.util.UUID;
import com.github.f4b6a3.uuid.util.UuidValidator;
public class Example3 {
public static void main(String[] args) {
String uuidString = "005056963AB75FD48BDC59C100314C40";
UUID uuid = UuidCreator.fromString(uuidString);
}
}
Project page: https://github.com/f4b6a3/uuid-creator