regex to extract all substrings between two characters or tags

I need to extract all strings surrounded by two characters (or maybe two tags)

this is what i have 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]); 

There are three objects in myArray, 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 am i wrong

+7
source share
2 answers

According to the documentation matchesInString:options:range: returns an array of NSTextCheckingResult not NSString s. You will need to iterate over the results and use 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]); } 
+20
source

Or that

 NSArray *results = [@"[db1]+[db2]+[db3]" matchWithRegex:@"\\[(.*?)\\]"]; //result = @["db1","db2,"db3"] 

With this category https://github.com/damienromito/NSString-Matcher

0
source

All Articles