Capture groups not working in NSRegularExpression

Maciej Swic picture Maciej Swic · Jul 25, 2011 · Viewed 20.4k times · Source

Why is this code only spitting out the entire regex match instead of the capture group?

Input

@"A long string containing Name:</td><td>A name here</td> amongst other things"

Output expected

A name here

Actual output

Name:</td><td>A name here</td>

Code

NSString *htmlString = @"A long string containing Name:</td><td>A name here</td> amongst other things";
NSRegularExpression *nameExpression = [NSRegularExpression regularExpressionWithPattern:@"Name:</td>.*\">(.*)</td>" options:NSRegularExpressionSearch error:nil];

NSArray *matches = [nameExpression matchesInString:htmlString
                                  options:0
                                    range:NSMakeRange(0, [htmlString length])];
for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *matchString = [htmlString substringWithRange:matchRange];
    NSLog(@"%@", matchString);
}

Code taken from Apple docs. I know there are other libraries to do this but i want to stick with what's built in for this task.

Answer

user756245 picture user756245 · Jul 26, 2011

You will access the first group range using :

for (NSTextCheckingResult *match in matches) {
    //NSRange matchRange = [match range];
    NSRange matchRange = [match rangeAtIndex:1];
    NSString *matchString = [htmlString substringWithRange:matchRange];
    NSLog(@"%@", matchString);
}