我试图从这个字符串中获取: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/