ios - 正则表达式匹配组不适用于 Objective-C

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

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

最佳答案

你得到了正确的匹配,只是你没有正确打印它们。您需要使用 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);
    }
}

关于ios - 正则表达式匹配组不适用于 Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28115181/

相关文章:

javascript - 涉及转义符号的正则表达式

objective-c - 同一 NSManagedObject 之间的多种关系

c++ - 我怎样才能忽略 Xcode 中的一些错误?

iphone - 核心数据错误?

objective-c - Shell 脚本调用错误

ios - 钥匙串(keychain)数据未存储在 iCloud 中

javascript - 对于 IOS Phonegap 应用程序,是否可以包含非应用程序本地的 javascript 文件

ios - 我应该在嵌套 block 中使用 weakSelf 吗?

regex - 用于从 MDX 查询中提取元素的正则表达式

python - 截断/修剪列表每一行的日期和时间