How to check the validity of a GUID (or UUID) using NSRegularExpression or any other effective way in Objective-C

Viewed 4500

The method should return TRUE if the NSString is something like @"{A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}" and FALSE for a NSString like @"bla bla bla"

I am using something like:

- (BOOL)isValidGUID {

    NSError *error;

    NSRange range = [[NSRegularExpression regularExpressionWithPattern:@"(?:(\\()|(\\{))?\\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-Z0-9]{12}\\b(?(1)\\))(?(2)\\})" options:NSRegularExpressionCaseInsensitive error:&error] rangeOfFirstMatchInString:self.GUID options:0 range:NSMakeRange(0, [self.GUID length])];

    if (self.GUID && range.location != NSNotFound && [self.GUID length] == 38) {

        return TRUE;

    } else {

        return NO;
    }
}

but it is not working as I have expected.

Important: GUID which I am using is enclosed by curly braces like this: {A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}

4 Answers

Consider the shortened UUID format. Use code below:

-(BOOL)isValidUUID:(NSString*)uuidString{   
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
if (uuid ) {
    return YES;
}

NSError *error;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"[^0-9|^a-f]" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [reg matchesInString:uuidString options:NSMatchingReportCompletion range:NSMakeRange(0, uuidString.length)];

if (matches.count == 0 && (uuidString.length == 4 || uuidString.length ==8) ) {
    return YES;
}else{
    return NO;
}
}
Related