正则表达式匹配组不在objective-c上工作

时间:2015-01-23 17:14:10

标签: ios objective-c regex

我试图从这个字符串中获取:5556007503140005 两个字符串。 " 555600750314"和" 0005"

我使用正则表达式^([a-z0-9]*)([0-9]{4})$在正则表达式工具上正常工作,但当我在我的代码上使用它时,我只得到1个匹配。

这是代码

-(NSDictionary *)parse_barcode:(NSString *)barcode {
    NSString *regexp = @"^([a-z0-9]*)([0-9]{4})$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regexp];

    if ([predicate evaluateWithObject:barcode]) {
        NSError *error;

        NSRegularExpression *regular_exp = [NSRegularExpression regularExpressionWithPattern:regexp options:0 error:&error];

        NSArray *matches = [regular_exp matchesInString:barcode options:0 range:NSMakeRange(0, [barcode length])];

        for (NSTextCheckingResult *match in matches) {
            NSLog(@"match %@ :%@",[barcode substringWithRange:[match range]], match);
        }

    }
    return nil;
}

但是匹配总是整个字符串(条形码)

1 个答案:

答案 0 :(得分:3)

你得到了正确的匹配,你只是没有正确打印它们。您需要使用numberOfRanges来获取各个(即括在括号中的部分),然后为每个组调用rangeAtIndex:,如下所示:

for (NSTextCheckingResult *match in matches) {
    for (int i = 0 ; i != match.numberOfRanges ; i++) {
        NSLog(@"match %d - %@ :%@", i, [barcode substringWithRange:[match rangeAtIndex:i]], match);
    }
}