正则表达式匹配搜索字符串
1.正则介绍:
特殊符号’^'和’$'。他们的作用是分别指出一个字符串的开始和结束。eg:
“^one”:表示所有以”one”开始的字符串(”one cat”,”one123″,·····);
类似于:- (BOOL)hasPrefix:(NSString *)aString;
“a dog$”:表示所以以”a dog”结尾的字符串(”it is a dog”,·····);
类似于:- (BOOL)hasSuffix:(NSString *)aString;
“^apple$”:表示开始和结尾都是”apple”的字符串,这个是唯一的~;
“banana”:表示任何包含”banana”的字符串。
2.正则和NSString结合使用,返回NSRange参数设置匹配的字体颜色。
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
NSString *searchText = @"rangeOfString"; NSRange range = [searchText rangeOfString:@"^[0-9]+$" options:NSRegularExpressionSearch]; if (range.location != NSNotFound) { NSLog(@"range :%@", [searchText substringWithRange:range]); }
3.使用 NSMutableAttributedString设置匹配中的自负为红色。
NSString *lbX = [NSString stringWithFormat:@"%@ (%@)",[dict valueForKey:@"FileLeafRef"] ,[dict valueForKey:@"ItemChildCount"] ]; NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:lbX]; [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchDocModel.fileNameRange]; cell.textLabel.attributedText = attributeStr;
4.在 UISerachBar的代理方法中开辟新线程去做匹配操作,匹配完成刷新视图。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ //开开启多线程匹配数据 if ((self.resultDatasource!=nil)&&(self.resultDatasource.count!=0)) { [self.resultDatasource removeAllObjects];//清空之前的搜索结果 } NSLog(@"当前的searchText是%@,搜索的长度是:%lu",searchText,searchText.length); __weak ATSDocViewController *weakSelf = self; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ for (NSDictionary *dic in arrTasks) { NSString *fileName = [[dic valueForKey:@"FileLeafRef"] lowercaseString]; NSRange fileNameRange = [fileName rangeOfString:[searchText lowercaseString] options:NSRegularExpressionSearch]; NSString *author = [[NSString stringWithFormat:@"%@ - %@",[dic valueForKey:@"Author"] ,[dic valueForKey:@"Modified"]] lowercaseString]; NSRange authorRange = [author rangeOfString:[searchText lowercaseString] options:NSRegularExpressionSearch]; NSRange modifiedRange = [author rangeOfString:[searchText lowercaseString] options:NSRegularExpressionSearch]; if (!((fileNameRange.location == NSNotFound)&&(authorRange.location == NSNotFound)&&(modifiedRange.location == NSNotFound))) { //如果有一个不是空的就加入数组 MatchDocModel *model = [[MatchDocModel alloc] init]; model.dic = dic; model.fileNameRange = fileNameRange; model.authorRange = authorRange; model.modifiedRange = modifiedRange; [weakSelf.resultDatasource addObject:model];//添加具体的搜索结果 } } NSLog(@"匹配结束,匹配的数量是:%lu个",weakSelf.resultDatasource.count); //刷新数据 dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf.resultTable reloadData];//刷新数据 }); }); }
以上代码为个人思路总结,各位不懂的不要照搬抄袭,对你没什么帮助。