Last active
October 29, 2019 20:05
-
-
Save dzenbot/e91a6fc7cd58fd597e35 to your computer and use it in GitHub Desktop.
NSString: Get all matching NSRange of a substring
This file contains hidden or 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
- (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