我正在使用正则表达式在文本块中搜索uuid。目前,我依赖于所有uuid都遵循8-4-4-4-12十六进制数字模式的假设。
有人能想到这样一个用例吗?在这个用例中,这个假设是无效的,并且会导致我错过一些uuid。
我正在使用正则表达式在文本块中搜索uuid。目前,我依赖于所有uuid都遵循8-4-4-4-12十六进制数字模式的假设。
有人能想到这样一个用例吗?在这个用例中,这个假设是无效的,并且会导致我错过一些uuid。
当前回答
在python re中,你可以从数字到大写alpha。所以. .
import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
这使得最简单的Python UUID正则表达式:
re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)
我将把使用timeit来比较它们的性能作为读者的练习。
享受。 保持python™!
注意:这些跨度也将匹配:;<=>?所以,如果你怀疑这可能会给你假阳性,不要走捷径。(感谢Oliver Aubert在评论中指出这一点。)
其他回答
根据定义,UUID是32个十六进制数字,用连字符分隔为5组,正如您所描述的那样。你不应该错过任何正则表达式。
http://en.wikipedia.org/wiki/Uuid#Definition
c++的变体:
#include <regex> // Required include
...
// Source string
std::wstring srcStr = L"String with GIUD: {4d36e96e-e325-11ce-bfc1-08002be10318} any text";
// Regex and match
std::wsmatch match;
std::wregex rx(L"(\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\})", std::regex_constants::icase);
// Search
std::regex_search(srcStr, match, rx);
// Result
std::wstring strGUID = match[1];
想要给出我的贡献,因为我的regex涵盖了OP的所有情况,并正确地将组方法上的所有相关数据分组(你不需要post处理字符串来获得uuid的每个部分,这个regex已经为你获得了它)
([\d\w]{8})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{12})|[{0x]*([\d\w]{8})[0x, ]{4}([\d\w]{4})[0x, ]{4}([\d\w]{4})[0x, {]{5}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})
官方uuid库使用以下正则表达式:
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i
见参考
对于在OS X上使用uuidgen生成的UUID,正则表达式模式为
[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}
验证与
uuidgen | grep -E "[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}"