我是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>club</strong>删除<strong></strong><strong>club</strong> )
另一个案例if text = "A fanclub is a group that is dedicated to a well-known person";注:“扇俱乐部”没有空格
结果-> 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>
有人能帮我做这件事吗?
发布于 2012-08-22 18:27:11
你可以试试这个:
keywords = "\b(" + r.Replace(keywords, @"|") + ")\b";\b -用于非字字符
发布于 2012-08-22 18:36:54
你的关键词应该是这样
string keywords = "\bgroup\b, \bperson\b, \bclub\b";\b会创建一个边界,这样fanclub就不匹配了!
https://stackoverflow.com/questions/12078961
复制相似问题