效果描述:
在textview上有一段文字,根据RegularExpression创建对应的正则表达式找出对应的文字,并进行高亮显示~
主要代码:
1.创建正则 NSRegularExpression
- (NSRegularExpression *)regularExpressionWithString:(NSString *)searchStr{
NSError *error = NULL;
//缩放的是整个单词
NSString *pattern = [NSString stringWithFormat:@"\\b%@\\b",searchStr];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
{
NSLog(@"正则表达式创建出错");
}
return regex;
}
提供一个工具类返回textview可见范围(当textview内容过长时,部分是看不到的)
// 返回textView可见的范围(textView内容过多少,有部分看不到)
- (NSRange)visibleRangeOfTextView:(UITextView *)textView
{
CGRect bounds = textView.bounds;
UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start;
UITextPosition *end = [textView characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
NSRange visibleRange = NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start],
[textView offsetFromPosition:start toPosition:end]);
NSLog(@"start:%@;end:%@,visibleRange:%@",start,end,NSStringFromRange(visibleRange));
return visibleRange;
}
2.搜索对应的字符串并进行设置
- (void)searchText:(NSString *)searchString{
NSRange visibleRange = [self visibleRangeOfTextView:self.textView];
//可见文字
NSMutableAttributedString *visibleAttributedText = [self.textView.attributedText attributedSubstringFromRange:visibleRange].mutableCopy;
NSString *visibleText = visibleAttributedText.string;
NSRange visibleTextRange = NSMakeRange(0, visibleText.length);
创建正则表达式规则 寻找匹配到的所有结果
NSRegularExpression *regex = [self regularExpressionWithString:searchString];
NSArray *matches = [regex matchesInString:visibleText options:NSMatchingReportProgress range:visibleTextRange];
for (NSTextCheckingResult *match in matches) {
[visibleAttributedText addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:match.range];
}
//改变背景色
CFRange visibleRange_CF = CFRangeMake(visibleRange.location, visibleRange.length);
NSMutableAttributedString *textViewAttributedString = self.textView.attributedText.mutableCopy;
CFAttributedStringReplaceAttributedString((__bridge CFMutableAttributedStringRef)(textViewAttributedString), visibleRange_CF, (__bridge CFAttributedStringRef)(visibleAttributedText));
self.textView.attributedText = textViewAttributedString;
}
4.测试代码
//搜索Purchases字符串
[self searchText:@"Purchases"];
本文主要内容是摘自raywenderlich NSRegularExpression Tutorial and Cheat Sheet 为了方便做个笔记只是单纯的将该部分内容拿出来测试下,有兴趣需要了解更多细节的可参考原文。