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

后端 未结 4 522
滥情空心
滥情空心 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:10

    This regex matches for me

    \A\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}\Z
    

    In short:

    • \A and \Z is the beginning and end of the string
    • \{ and \} is escaped curly bracets
    • [A-F0-9]{8} is exactly 8 characters of either 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

    As an NSRegularExpression it would look like this

    NSError *error = NULL;
    NSRegularExpression *regex = 
      [NSRegularExpression regularExpressionWithPattern:@"\\A\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\}\\Z" 
                                                options:NSRegularExpressionAnchorsMatchLines 
                                                  error:&error];
    // use the regex to match the string ...
    
    0 讨论(0)
  • 2021-01-12 09:13

    This function will do the job..

    -(BOOL)isValidUUID : (NSString *)UUIDString
    {
         return (bool)[[NSUUID alloc] initWithUUIDString:U‌​UIDString]; 
    }
    

    Thanks @Erzékiel

    0 讨论(0)
  • 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;
    }
    }
    
    0 讨论(0)
  • 2021-01-12 09:18

    You can use the following method to check this:

    - (BOOL)isUUID:(NSString *)inputStr
    {
        BOOL isUUID = FALSE;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" options:NSRegularExpressionCaseInsensitive error:nil];
        NSInteger matches = [regex numberOfMatchesInString:inputStr options:0 range:NSMakeRange(0, [inputStr length])];
        if(matches == 1)
        {
           isUUID = TRUE;
        }
        return isUUID;
    }
    
    0 讨论(0)
提交回复
热议问题