Skip to content

Instantly share code, notes, and snippets.

@dzenbot
Last active October 29, 2019 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzenbot/e91a6fc7cd58fd597e35 to your computer and use it in GitHub Desktop.
Save dzenbot/e91a6fc7cd58fd597e35 to your computer and use it in GitHub Desktop.
NSString: Get all matching NSRange of a substring
- (NSArray *)rangesInSubstring:(NSString *)substring
{
NSError *error = NULL;
NSString *regex = [NSString stringWithFormat:@"\\b%@", substring];
NSRegularExpression *regExpression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSMutableArray *ranges = [NSMutableArray array];
NSArray *matches = [regExpression matchesInString:self options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
for (NSTextCheckingResult *match in matches) {
[ranges addObject:[NSValue valueWithRange:match.range]];
}
return ranges;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment