【问题标题】:Highlighting whole word in HTML string using C# regexp使用 C# 正则表达式突出显示 HTML 字符串中的整个单词
【发布时间】: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();
}

【问题讨论】:

    标签: c# html regex


    【解决方案1】:

    您需要使用捕获的.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 是围绕突出显示的单词的可选连字符(使用 (-)? 捕获)。

    【讨论】:

    • 谢谢,它有效!我很惊讶地看到 $2 在没有连字符的情况下也能捕捉到这个词。
    • 捕获组就是这样工作的,如果你在正则表达式中设置它,它会返回一个组,无论是否为空。
    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多