2

I am a newbie with Regex so I need some help from my trouble.

This is my code:

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";

when i call HighlightKeywords(string keywords, string text);

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

But if string text = "A fan <strong>club</strong> is a group that is dedicated to a well-known person";

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

WORK FAIL (I want remove <strong></strong><strong>club</strong> with only <strong>club</strong>)

Another case if text = "A fanclub is a group that is dedicated to a well-known person"; note: "fanclub" no space

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

But i want get result --> A fanclub is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

So Can any one help me how to do this ?

4

2 回答 2

0

你可以试试这个:

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

\b - 非单词字符

于 2012-08-22T18:27:11.837 回答
0

你的关键字应该是这样的

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

\b会创建一个边界,所以fanclub不匹配!

于 2012-08-22T18:36:54.930 回答