我编写了一个方法来突出显示 HTML 字符串中的关键字。它返回更新后的字符串和匹配关键字的列表。 如果该单词显示为整个单词或带有破折号,我想匹配该单词。 但如果它与破折号一起出现,则包含破折号的单词将突出显示并返回。
例如,如果单词是 locks
并且 HTML 包含 He -locks- thedoor
,则该单词周围的破折号也会突出显示:
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();
}
最佳答案
您需要使用捕获的.Groups[2].Value
而不是Match.Value
因为您的正则表达式有 3 个捕获组,并且第二个包含您突出显示的关键字:
foreach (Match match in regex.Matches(text))
{
matchingKeywords.Add(match.Groups[2].Value);
}
if (bHighlight)
{
text = regex.Replace(text, string.Format("$1<span style=\"background-color:yellow\">{0}</span>$3", "$2"));
}
match.Groups[2].Value
用于foreach
然后$2
是对 regex.Replace
中捕获的关键字的反向引用替换字符串。 $1
和$3
是突出显示的单词周围的可选连字符(使用 (-)?
捕获)。
关于c# - 使用 C# 正则表达式突出显示 HTML 字符串中的整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290291/