regex to extract all the substrings between two characters or tags

objective-c, regex

Solution

According to the documentation `matchesInString:options:range:` returns an array of `NSTextCheckingResult`s not `NSString`s. You will need to loop over the results and use the ranges to get the substrings.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL];

NSString *input = @"[db1]+[db2]+[db3]";
NSArray *myArray = [regex matchesInString:input options:0 range:NSMakeRange(0, [input length])] ;

NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]];

for (NSTextCheckingResult *match in myArray) {
     NSRange matchRange = [match rangeAtIndex:1];
     [matches addObject:[input substringWithRange:matchRange]];
     NSLog(@"%@", [matches lastObject]);
}

Problem

I need to extract all the strings surrounded by two characters (or maybe two tags) this is what I've done so far: ``` NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL]; NSArray *myArray = [regex matchesInString:@"[db1]+[db2]+[db3]" options:0 range:NSMakeRange(0, [@"[db1]+[db2]+[db3]" length])] ; NSLog(@"%@",[myArray objectAtIndex:0]); NSLog(@"%@",[myArray objectAtIndex:1]); NSLog(@"%@",[myArray objectAtIndex:2]); ``` In myArray there are correctly three objects but NSlog prints this: ``` <NSSimpleRegularExpressionCheckingResult: 0x926ec30>{0, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} <NSSimpleRegularExpressionCheckingResult: 0x926eb30>{6, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} <NSSimpleRegularExpressionCheckingResult: 0x926eb50>{12, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} ``` instead of db1, db2 and db3 where I'm wrong?

Original source