Reputation: 2449
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?
Upvotes: 7
Views: 7765
Reputation: 10055
Or this
NSArray *results = [@"[db1]+[db2]+[db3]" matchWithRegex:@"\\[(.*?)\\]"];
//result = @["db1","db2,"db3"]
With this category https://github.com/damienromito/NSString-Matcher
Upvotes: 0
Reputation: 57169
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]);
}
Upvotes: 20