我需要在一个文本块中突出显示搜索字词。
我最初的想法是通过搜索术语循环。但是有更简单的方法吗?
以下是我正在考虑使用循环...
public string HighlightText(string inputText)
{
string[] sessionPhrases = (string[])Session["KeywordPhrase"];
string description = inputText;
foreach (string field in sessionPhrases)
{
Regex expression = new Regex(field, RegexOptions.IgnoreCase);
description = expression.Replace(description,
new MatchEvaluator(ReplaceKeywords));
}
return description;
}
public string ReplaceKeywords(Match m)
{
return "<span style='color:red;'>" + m.Value + "</span>";
}
答案 0 :(得分:1)
您可以使用以下内容替换循环:
string[] phrases = ...
var re = String.Join("|", phrases.Select(s => Regex.Escape(s)).ToArray());
text = Regex.Replace(re, text, new MatchEvaluator(SomeFunction), RegexOptions.IgnoreCase);
答案 1 :(得分:0)
延伸Qtax的回答:
phrases = ...
// Use Regex.Escape to prevent ., (, * and other special characters to break the search
string re = String.Join("|", phrases.Select(s => Regex.Escape(s)).ToArray());
// Use \b (expression) \b to ensure you're only matching whole words, not partial words
re = @"\b(?:" +re + @")\b"
// use a simple replacement pattern instead of a MatchEvaluator
string replacement = "<span style='color:red;'>$0</span>";
text = Regex.Replace(re, text, replacement, RegexOptions.IgnoreCase);
如果您已经在HTML中替换数据,那么使用Regex替换内容中的任何内容可能不是一个好主意,您最终可能会得到:
<<span style='color:red;'>script</span>>
如果有人正在搜索术语脚本。
为防止这种情况发生,you could use the HTML Agility Pack in combination with Regex。
You might also want to check out this post which deals with a very similar issue