返回
正则表达式教程:GUID/UUID 匹配
正则表达式
2024-02-28 15:51:21
一、正则解释
正则表达式:/^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}$/i
解释:
^
: 匹配字符串的开头[a-f\d]{4}
: 匹配 4 个十六进制数字或数字(?:[a-f\d]{4}-){4}
: 匹配 4 组 4 个十六进制数字或数字,并以连字符分隔[a-f\d]{12}
: 匹配 12 个十六进制数字或数字$
: 匹配字符串的末尾i
: 不区分大小写
二、使用场景
这个正则表达式用于匹配 GUID(全局唯一标识符)或 UUID(通用唯一标识符)格式的字符串。GUID/UUID 通常用于数据库主键、唯一标识符或跟踪事务。
三、代码示例
JavaScript
const regex = /^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}$/i;
const testStrings = [
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000",
];
for (const testString of testStrings) {
console.log(`${testString} ${regex.test(testString) ? "匹配" : "不匹配"}`);
}
Java
import java.util.regex.Pattern;
public class GuidMatcher {
private static final Pattern GUID_PATTERN = Pattern.compile("^[a-f\\d]{4}(?:[a-f\\d]{4}-){4}[a-f\\d]{12}import java.util.regex.Pattern;
public class GuidMatcher {
private static final Pattern GUID_PATTERN = Pattern.compile("^[a-f\\d]{4}(?:[a-f\\d]{4}-){4}[a-f\\d]{12}$", Pattern.CASE_INSENSITIVE);
public static void main(String[] args) {
String[] testStrings = {
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000"
};
for (String testString : testStrings) {
System.out.println(testString + " " + (GUID_PATTERN.matcher(testString).matches() ? "匹配" : "不匹配"));
}
}
}
quot;, Pattern.CASE_INSENSITIVE);
public static void main(String[] args) {
String[] testStrings = {
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000"
};
for (String testString : testStrings) {
System.out.println(testString + " " + (GUID_PATTERN.matcher(testString).matches() ? "匹配" : "不匹配"));
}
}
}
PHP
<?php
$regex = "/^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}$/i";
$testStrings = [
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000"
];
foreach ($testStrings as $testString) {
echo "$testString " . (preg_match($regex, $testString) ? "匹配" : "不匹配") . PHP_EOL;
}
Python
import re
regex = r"^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}import re
regex = r"^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}$"
testStrings = [
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000"
]
for testString in testStrings:
print(f"{testString} {(re.match(regex, testString) is not None)}")
quot;
testStrings = [
"e155518c-ca1b-443c-9be9-fe90fdab7345",
"41E3DAF5-6E37-4BCC-9F8E-0D9521E2AA8D",
"00000000-0000-0000-0000-000000000000"
]
for testString in testStrings:
print(f"{testString} {(re.match(regex, testString) is not None)}")