我正在寻找一些简单的 iPhone 正则表达式来验证 NSString 是否为有效的十六进制格式,仅包含 0-9 和 af 的字符。GUID 也是如此。或者是否已经内置了一个函数来检查 GUID 是否有效?
我只发现了一些关于创建 GUID 的帖子。这个SO 答案是以我正在使用的格式创建 GUID。
示例 GUID
ADD2B9F7-A699-4EF3-9A70-130B92154B11
为了简化 Zaph 的正确答案,只需将此方法添加到 NSString 上的类别中:
-(BOOL) isGuid {
NSString *regexString = @"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";
NSRange guidValidationRange = [self rangeOfString:regexString options:NSRegularExpressionSearch];
return (guidValidationRange.location == 0 && guidValidationRange.length == self.length);
}
一种方法是使用NSCharacterSet
:
NSString *testCharacters = @"ABCDEFabcdef0123456789-";
NSCharacterSet *testCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:testCharacters] invertedSet];
NSString *testString1 = @"ADD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range1 = [testString1 rangeOfCharacterFromSet:testCharacterSet];
NSLog(@"testString1: %@", (range1.location == NSNotFound) ? @"Good" : @"Bad");
NSString *testString2 = @"zDD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range2 = [testString2 rangeOfCharacterFromSet:testCharacterSet];
NSLog(@"testString2: %@", (range2.location == NSNotFound) ? @"Good" : @"Bad");
NSLog 输出:
testString1: Good
testString2: Bad
或使用 RE:
NSString *reString = @"[a-fA-F0-9-]+";
NSString *testString1 = @"ADD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range1 = [testString1 rangeOfString:reString options:NSRegularExpressionSearch];
NSLog(@"testString1: %@", (range1.location != NSNotFound && range1.length == testString1.length) ? @"Good" : @"Bad");
NSString *testString2 = @"zDD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range2 = [testString2 rangeOfString:reString options:NSRegularExpressionSearch];
NSLog(@"testString2: %@", (range1.location != NSNotFound && range2.length == testString2.length) ? @"Good" : @"Bad");
对于更严格的 GUID 匹配:
NSString *reString = @"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";