常規(guī)方法:
//獲取一個字符在字符串中出現(xiàn)的所有位置 返回一個被NSValue包裝的NSRange數(shù)組
- (NSArray *)rangeOfSubString:(NSString *)subStr inString:(NSString *)wholeString {
if (subStr == nil && [subStr isEqualToString:@""]) {
return nil;
}
NSMutableArray *aRangeArray = [NSMutableArray array];
NSString *temp;
for (int i = 0; i < wholeString.length; i ++) {
temp = [wholeString substringWithRange:NSMakeRange(i, subStr.length)];
if ([temp isEqualToString:subStr]) {
NSRange range = {i,subStr.length};
[aRangeArray addObject:[NSValue valueWithRange:range]];
}
}
return aRangeArray;
}
正則方法:
-(NSArray *)matchCharacters:(NSString *)targetString inWholeString:(NSString *)wholeString{
if (targetString.length==0 || !targetString) {
return nil;
}
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"%@",targetString] options:0 error:nil];
NSArray *matches = [regex matchesInString:wholeString options:0 range:NSMakeRange(0,wholeString.length)];
NSMutableArray * aRangeArray = [NSMutableArray array];
for(NSTextCheckingResult *result in [matches objectEnumerator]) {
NSRange matchRange = [result range];
[aRangeArray addObject:[NSValue valueWithRange:matchRange]];
}
return aRangeArray;
}