c# - 如何在特殊条件下使用 C# 中的正则表达式突出显示关键字?

标签 c# regex syntax-highlighting

我是 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> 工作正确

但是如果 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></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 - 非单词字符

关于c# - 如何在特殊条件下使用 C# 中的正则表达式突出显示关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078961/

相关文章:

c# - 使用基本字符串操作的字符串模式匹配

c# - visual studio C# express 中 Win32_NetworkAdapter 的引用命名空间是什么?

javascript - 查找 <colgroup> 的正则表达式组

regex - 分隔电子邮件地址的正则表达式

可以突出显示所选单词的所有实例的 Linux 编辑器

c# - 在反射方法调用中访问网络共享

c# - StructureMap 中的命名实例和默认实例?

php - 使用正则表达式从 HTML 页面中提取 JSON (PHP)

c# - CSS:使用宽度百分比定位子表?