0

I was searching around finding some easy regex for iPhone to validate if a NSString is in a valid Hex format, containing only characters from 0-9 and a-f. The same for GUID's. Or is there already a function built in to check if a GUID is valid?

I only found some posts about creating GUIDs. This SO answer is creating GUID's in the format I'm using them.

Sample GUID

ADD2B9F7-A699-4EF3-9A70-130B92154B11
Community
  • 1
  • 1
Arndt Bieberstein
  • 1,128
  • 1
  • 14
  • 28

2 Answers2

4

To simplify Zaph's correct answer, just add this method to a category on 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);
}
Adam Lockhart
  • 1,165
  • 1
  • 10
  • 13
3

One way is to use 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 output:

testString1: Good
testString2: Bad

or using REs:

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");

For a more rigorous GUID match:

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}";
zaph
  • 111,848
  • 21
  • 189
  • 228