的擴展,上述問題的答案。 (沒有足夠的口碑給評論)
爲了避免跨度被替換時,搜索標準爲[跨度潘安一],找到的詞替換爲別的東西不是替換回來......不是很有效,雖然...
public string Highlight(string input)
{
if (input == string.Empty || searchQuery == string.Empty)
{
return input;
}
string[] sKeywords = searchQuery.Replace("~",String.Empty).Replace(" "," ").Trim().Split(' ');
int totalCount = sKeywords.Length + 1;
string[] sHighlights = new string[totalCount];
int count = 0;
input = Regex.Replace(input, Regex.Escape(searchQuery.Trim()), string.Format("~{0}~", count), RegexOptions.IgnoreCase);
sHighlights[count] = string.Format("<span class=\"highlight\">{0}</span>", searchQuery);
foreach (string sKeyword in sKeywords.OrderByDescending(s => s.Length))
{
count++;
input = Regex.Replace(input, Regex.Escape(sKeyword), string.Format("~{0}~", count), RegexOptions.IgnoreCase);
sHighlights[count] = string.Format("<span class=\"highlight\">{0}</span>", sKeyword);
}
for (int i = totalCount - 1; i >= 0; i--)
{
input = Regex.Replace(input, "\\~" + i + "\\~", sHighlights[i], RegexOptions.IgnoreCase);
}
return input;
}
首先,這是怎麼回事的話中承認部分匹配。您的正則僅需要做整個單詞替換。其次,你可以輸入'」「',而不是'Convert.ToChar(」「)' – Richard 2009-10-27 14:52:26
感謝理查德 - 很好的提示字符,我知道必須有一個更好的方式,但它並沒有點擊RE部分匹配,這就是我在後。這種情況下,因爲搜索使用通配符(因此需要使事情更清晰並突出顯示)。 – TimS 2009-10-27 15:32:28
謝謝!這對我很好。 – 2010-04-15 23:58:49