简体   繁体   中英

Regexp matching group not working on objective-c

I'm trying to get from this string: 5556007503140005 Two strings. "555600750314" and "0005"

I'm Using the regexp ^([a-z0-9]*)([0-9]{4})$ that works fine on the regexp tools, but when i use this on my code I only get 1 match.

this is the code

-(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;
}

But the match is always the entire string (Barcode)

You get the right match, you are just not printing them correctly. You need to use numberOfRanges to get the individual groups (ie sections enclosed in parentheses), and then call rangeAtIndex: for each group, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM