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

后端 未结 4 556
滥情空心
滥情空心 2021-01-12 08:58

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

4条回答
  •  温柔的废话
    2021-01-12 09:14

    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;
    }
    }
    

提交回复
热议问题