iOS Regex匹配关键字并修改颜色
引入第三方框架RegexKitLite
/**
* 根据传入的文字返回一个符合规则的富文本
*
* @param title 匹配的文字
*
* @return 创建的富文本
*/
-(NSAttributedString *)titleLabText:(NSString *)title
{
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:title];
//匹配搜索关键字,并且改变颜色
if(self.keyWords.length >0)
{
[title enumerateStringsMatchedByRegex:self.keyWords usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
[attributeString addAttribute:NSForegroundColorAttributeName value:kSearchKeyWordsColor range:*capturedRanges];
}];
}
return attributeString;
}