2

私は正規表現の初心者なので、トラブルからの助けが必要です。

これは私のコードです:

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>

WORK FAIL<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>

誰でもこれを行う方法を手伝ってもらえますか?

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 に答える