Named capture groups with NSRegularExpression

后端 未结 4 2049
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 00:05

Does NSRegularExpression support named capture groups? It doesn\'t look like it from the documentation, but I wanted to check before I explore alternative solut

4条回答
  •  孤城傲影
    2020-12-29 00:50

    Named grouping is not supported in iOS, all you can do as I see is to make use of Enum:

    Enum:

    typedef enum
    {
        kDayGroup = 1,
        kMonthGroup,
        kYearGroup
    } RegexDateGroupsSequence;
    

    Sample Code:

    NSString *string = @"07-12-2014";
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{2})\\-(\\d{2})\\-(\\d{4}|\\d{2})"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *matches = [regex matchesInString:string
                                      options:0
                                        range:NSMakeRange(0, [string length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *day = [string substringWithRange:[match rangeAtIndex:kDayGroup]];
        NSString *month = [string substringWithRange:[match rangeAtIndex:kMonthGroup]];
        NSString *year = [string substringWithRange:[match rangeAtIndex:kYearGroup]];
    
    
        NSLog(@"Day: %@, Month: %@, Year: %@", day, month, year);
    }
    

提交回复
热议问题