如何检查变量是否包含有效的UUID/GUID标识符?
我目前只对验证类型1和4感兴趣,但这不应该成为您回答的限制。
如何检查变量是否包含有效的UUID/GUID标识符?
我目前只对验证类型1和4感兴趣,但这不应该成为您回答的限制。
当前回答
使用.match()方法检查String是否为UUID。
public boolean isUUID(String s){
return s.match("^[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}$");
}
其他回答
感谢@usertatha做了一些修改
function isUUID ( uuid ) {
let s = "" + uuid;
s = s.match('^[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}$');
if (s === null) {
return false;
}
return true;
}
我向Apache Commons validator添加了一个UUID验证器。它还没有合并,但你可以在这里投票:
https://github.com/apache/commons-validator/pull/68
正则表达式来拯救
/^[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('01234567-9ABC-DEF0-1234-56789ABCDEF0');
或者用括号
/^\{?[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}\}?$/
版本1到5,当version被省略时不使用多版本正则表达式。
const uuid_patterns = { 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i }; const isUUID = (input, version) => { if(typeof input === "string"){ if(Object.keys(uuid_patterns).includes(typeof version === "string" ? version : String(version))){ return uuid_patterns[version].test(input); } else { return Object.values(uuid_patterns).some(pattern => pattern.test(input)); } } return false; } // Testing let valid = [ 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', 'A987FBC9-4BED-4078-8F07-9141BA07C9F3', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', ]; let invalid = [ '', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', 'A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx', 'A987FBC94BED3078CF079141BA07C9F3', '934859', '987FBC9-4BED-3078-CF07A-9141BA07C9F3', 'AAAAAAAA-1111-1111-AAAG-111111111111', ]; valid.forEach(test => console.log("Valid case, result: "+isUUID(test))); invalid.forEach(test => console.log("Invalid case, result: "+isUUID(test)));
我有这个函数,但本质上它和公认的答案是一样的。
export default function isUuid(uuid: string, isNullable: boolean = false): boolean {
return isNullable
? /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid)
: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);
}