D语言判断字符串是否为有效UUID的几种方法
在D语言中,可以使用正则表达式、标准库函数和第三方库等方式实现判断一个字符是否是有效UUID。
- 正则表达式实现:
import std.regex;
bool isUuid(string str){
auto uuidRegex = regex(`^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$`);
return uuidRegex.match(str).length == 1;
}
// 测试代码
void main(){
assert(isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'));
assert(!isUuid('helloworld'));
}
- 标准库函数实现:
import std.algorithm : canFind, filter;
import std.ascii : isHexDigit;
import std.string : split;
bool isUuid(string str){
auto parts = str.split('-');
if (parts.length != 5) return false;
foreach (part; parts){
if (part.length != 4) return false;
if (!part.filter!(c => isHexDigit(c)).canFind!(c => c.isUpper)) return false;
}
return true;
}
// 测试代码
void main(){
assert(isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'));
assert(!isUuid('helloworld'));
}
- 第三方库uuid实现:
可以使用第三方库uuid来验证UUID的有效性。
import uuid;
bool isUuid(string str){
try {
auto u = UUID.fromString(str);
return true;
} catch (Exception e) {
return false;
}
}
// 测试代码
void main(){
assert(isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'));
assert(!isUuid('helloworld'));
}
原文地址: https://www.cveoy.top/t/topic/ocus 著作权归作者所有。请勿转载和采集!