我正在寻找一些易于使用iPhone的正则表达式,以验证NSString是否为有效的十六进制格式,仅包含0-9和a-f中的字符。对于GUID来说也一样。或者是否已经内置了一个函数来检查GUID是否有效?
我只发现了一些关于创建GUID的帖子。 This所以答案是以我正在使用它们的格式创建GUID。
示例GUID
ADD2B9F7-A699-4EF3-9A70-130B92154B11
答案 0 :(得分:4)
要简化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);
}
答案 1 :(得分:3)
一种方法是使用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}";