Created
February 24, 2012 01:28
-
-
Save rsattar/1896546 to your computer and use it in GitHub Desktop.
RegexKitLite's arrayOfCaptureComponentsMatchedByRegex: written using NSRegularExpression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code! Worked like a charm! :D