【发布时间】:2015-05-17 18:06:25
【问题描述】:
我编写了一个突出显示 HTML 字符串中的关键字的方法。它返回更新后的字符串和匹配关键字的列表。 如果它以整个单词或破折号出现,我想匹配该单词。 但如果出现破折号,则包含破折号的单词会突出显示并返回。
例如,如果单词是 locks 并且 HTML 包含 He -locks- the door,那么单词周围的破折号也会突出显示:
He <span style=\"background-color:yellow\">-locks-</span> the door.
代替:
He -<span style=\"background-color:yellow\">locks</span>- the door.
另外,返回的列表包含-locks-而不是locks。
我可以做些什么来获得预期的结果?
这是我的代码:
private static List<string> FindKeywords(IEnumerable<string> words, bool bHighlight, ref string text)
{
HashSet<String> matchingKeywords = new HashSet<string>(new CaseInsensitiveComparer());
string allWords = "\\b(-)?(" + words.Aggregate((list, word) => list + "|" + word) + ")(-)?\\b";
Regex regex = new Regex(allWords, RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match match in regex.Matches(text))
{
matchingKeywords.Add(match.Value);
}
if (bHighlight)
{
text = regex.Replace(text, string.Format("<span style=\"background-color:yellow\">{0}</span>", "$0"));
}
return matchingKeywords.ToList();
}
【问题讨论】: