我想搜索字符串中的搜索字詞並突出顯示字符串中的所有匹配項。搜索NSString並使用省略號顯示結果
應該顯示搜索詞周圍的一些文字(...),搜索詞應該用粗體字樣(NSMutableAttributedString)。
示例:搜索 「文本」
...樣品文本喇嘛......更多文本布拉布拉......喇嘛文本布拉布拉...
NSString *haystackString = [[self.searchResults objectAtIndex:indexPath.row] stripHTML];
NSString *needleString = self.searchDisplayController.searchBar.text;
if (!self.searchRegex) {
self.searchRegex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(?:\\S+\\s)?\\S*%@\\S*(?:\\s\\S+)?", needleString] options:(NSRegularExpressionDotMatchesLineSeparators + NSRegularExpressionCaseInsensitive) error:nil];
}
NSArray *matches = [self.searchRegex matchesInString:haystackString options:kNilOptions range:NSMakeRange(0, haystackString.length)];
NSMutableString *tempString = [[NSMutableString alloc] init];
for (NSTextCheckingResult *match in matches) {
[tempString appendString:@"..."];
[tempString appendString:[haystackString substringWithRange:[match rangeAtIndex:0]]];
[tempString appendString:@"..."];
}
if (tempString) {
cell.textLabel.text = tempString;
}
我當前的代碼似乎是緩慢和不支持NSMutableAttributedString呢。有更好的解決方案嗎?謝謝!
您是否嘗試過使用掃描儀而不是正則表達式? – Wain
我聽說NSScanner應該更快,但我不知道如何做到這一點與上面的帖子想要的輸出:{點} {前面的字} {空間} {searchterm粗體字} {空間} {word after} {dots} –