Skip to content

Instantly share code, notes, and snippets.

@rsattar
Created February 24, 2012 01:28
Show Gist options
  • Save rsattar/1896546 to your computer and use it in GitHub Desktop.
Save rsattar/1896546 to your computer and use it in GitHub Desktop.
RegexKitLite's arrayOfCaptureComponentsMatchedByRegex: written using NSRegularExpression
// I had a need to replace the use of RegexKitLite's arrayOfCaptureComponentsMatchedByRegex with
// the built-in NSRegularExpression in iOS 5+, and didn't find an existing example, so I wrote one:
- (NSArray *) arrayOfCaptureComponentsOfString:(NSString *)data matchedByRegex:(NSString *)regex
{
NSError *error = NULL;
NSRegularExpression *regExpression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSMutableArray *test = [NSMutableArray array];
NSArray *matches = [regExpression matchesInString:data options:NSRegularExpressionSearch range:NSMakeRange(0, data.length)];
for(NSTextCheckingResult *match in matches) {
NSMutableArray *result = [NSMutableArray arrayWithCapacity:match.numberOfRanges];
for(NSInteger i=0; i<match.numberOfRanges; i++) {
NSRange matchRange = [match rangeAtIndex:i];
NSString *matchStr = nil;
if(matchRange.location != NSNotFound) {
matchStr = [data substringWithRange:matchRange];
} else {
matchStr = @"";
}
[result addObject:matchStr];
}
[test addObject:result];
}
return test;
}
@pawelkata
Copy link

Thanks for the code! Worked like a charm! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment