IM里面,经常会用到@所有人功能,对于@关键字要进行常亮,这就要求我们不得不快速匹配获取对应的range!
以下给出参考源码
@"@[^\\s]+\\s"
NSString *textStr = @"@1111111 @24234234234 @433 @rrr @";
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:textStr];
[attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0] range:NSMakeRange(0, textStr.length)];
NSArray *ranges = [textStr mutableRangeOfString:@"@[^\\s]+\\s"];
[ranges enumerateObjectsUsingBlock:^(NSValue *rangeValue, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange range = [rangeValue rangeValue];
[attStr addAttribute:NSForegroundColorAttributeName value:ZSMainBlue1 range:range];
}];
return attStr;
给NSSstring一个Category扩展方法如下:
- (NSArray <NSValue*>*)mutableRangeOfString:(NSString *)searchString
{
NSString *parten = [NSString stringWithString:searchString];
NSError* error = NULL;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:NSRegularExpressionCaseInsensitive error:&error];
NSMutableArray *list = [NSMutableArray arrayWithCapacity:0];
NSArray* match = [reg matchesInString:self options:NSMatchingReportCompletion range:NSMakeRange(0, [self length])];
[match enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
{
NSRange range = [obj range];
[list addObject:[NSValue valueWithRange:range]];
}];
return list;
}