我是 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/