繁体   English   中英

特殊条件下如何在C#中使用Regex突出显示关键字?

[英]How highlight keyword using Regex in C# with special condition?

我是Regex的新手,所以我需要一些麻烦的帮助。

这是我的代码:

private static string MatchEval(Match match)
{
    if (match.Groups[1].Success)    
        return "<strong>" + match.ToString() + "</strong>";
    return "";
}

private static string HighlightKeywords(string keywords, string text)
{   
    Regex r = new Regex(@", ?");
    keywords = "(" + r.Replace(keywords, @"|") + ")";   
    r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase); 
    return r.Replace(text, new MatchEvaluator(MatchEval));
}

string keywords = "group, person, club";
string text = "A fan club is a group that is dedicated to a well-known person";

当我调用HighlightKeywords(string keywords, string text);

- >结果: A fan <strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong> WORK CORRECT

但是,如果string text = "A fan <strong>club</strong> is a group that is dedicated to a well-known person";

->结果: A fan <strong></strong><strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

失败 (我想仅用<strong>club</strong>删除<strong></strong><strong>club</strong> <strong>club</strong>

另一种情况是, if text = "A fanclub is a group that is dedicated to a well-known person"; 注意:“ fanclub ”没有空格

结果-> A fan<strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

但我想获得结果-> A fanclub is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

那么,有人可以帮我怎么做吗?

您可以尝试以下方法:

keywords = "\b(" + r.Replace(keywords, @"|") + ")\b";

\\ b-对于非文字字符

您的关键字应该像这样

string keywords = "\bgroup\b, \bperson\b, \bclub\b";

\\b将创建边界,因此fanclub将不匹配!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM