[英]How to replace occurrences of multiple strings with multiple other strings [NSString]
[英]Replacing occurrences of strings in NSString while maintaining case of original string
我有一些使用UIWebview顯示的本地HTML和CSS。 我想結合搜索命中突出顯示。
這是我的突出方法:
-(void) highlightsSearchTerm:(NSString *)searchTerm
{
NSString *highlightedSearchTerm = [NSString stringWithFormat:@"<span class='highlight'>%@</span>",searchTerm];
NSString *highlightedArticle = [article.articleHTML stringByReplacingOccurrencesOfString:searchTerm withString:highlightedSearchTerm options:NSCaseInsensitiveSearch range:NSMakeRange(0, [article.articleHTML length])];
article.articleHTML = highlightedArticle;
}
這個問題是它用例如Obama
取代了obama
(注意案例)。 我想保留原始文章的案例,同時結合點擊突出顯示。
我希望有一個更優雅的解決方案,而不是手動查找每個命中術語的起始和結束索引,然后分別插入<span class="highlights">
和''。
基本上我想要的東西:
+ [NSString stringByWrappingExistingString:(NSString *)stringToWrap withString:(NSString *)wrappingString options:NSCaseInsensitiveCompare];
有什么想法嗎?
您可以使用NSRegularExpression
執行此操作(直接鍵入代碼,檢查錯誤):
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"Obama"
options:NSRegularExpressionCaseInsensitive
error:NULL];
NSString *output = [re stringByReplacingMatchesInString:inputString
options:0
range:NSMakeRange(0, inputString.length)
withTemplate:@"<span class='highlight'>$0</span>"];
在這種情況下,正則表達式搜索字符串@"Obama"
很簡單,因為您正在尋找文字匹配; 選項options:NSRegularExpressionCaseInsensitive
使匹配不區分大小寫。
雖然該示例使用文字奧巴馬 ,但顯然可以動態構造字符串; 但是在這種情況下要小心使用包含正則表達式元字符的字符串,它們將需要進行轉義。
替換模板包含$0
,它將被匹配的內容替換( 確切地說 ,保留大小寫)。
這里是:
-(void) highlightsSearchTerm:(NSString *)searchTerm
{
NSString *openSpan = @"<span class='highlight'>";
NSString *closeSpan = @"</span>";
NSRange searchRange = NSMakeRange(0, article.articleHTML.length);
NSRange foundRange;
NSString *highlightedArticle = article.articleHTML;
while (searchRange.location < highlightedArticle.length)
{
searchRange.length = highlightedArticle.length - searchRange.location;
foundRange = [highlightedArticle rangeOfString:searchTerm options:NSCaseInsensitiveSearch range:searchRange];
if (foundRange.location != NSNotFound)
{
// found an occurrence of the substring! do stuff here
searchRange.location = foundRange.location + foundRange.length;
NSString *casePreservedSearchQuery = [highlightedArticle substringWithRange:foundRange];
NSString *styledSearchQuery = [NSString stringWithFormat:@"%@%@%@", openSpan, casePreservedSearchQuery, closeSpan];
highlightedArticle = [highlightedArticle stringByReplacingCharactersInRange:foundRange withString:styledSearchQuery];
//increase the current location by the length of new string - search query length
searchRange.location = searchRange.location + [styledSearchQuery length] - [casePreservedSearchQuery length];
}
else
{
break;
}
}
// no more substring to find
article.articleHTML = highlightedArticle;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.