2010-02-26 2 views
0

긴 텍스트와 일부 키워드가 있습니다. 나는이 텍스트를 본문에서 강조하고 싶다.regexp를 사용하여 키워드로 단어 전체를 강조 표시하려면 어떻게합니까?

 private static string HighlightKeywords2(string keywords, string text) 
     { 
      // Swap out the ,<space> for pipes and add the braces 
      Regex r = new Regex(@", ?"); 
      keywords = "(" + r.Replace(keywords, @"|") + ")"; 

      // Get ready to replace the keywords 
      r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase); 

      // Do the replace 
      return r.Replace(text, new MatchEvaluator(MatchEval2)); 
     } 


     private static string MatchEval2(Match match) 
     { 
      if (match.Groups[1].Success) 
      { 
       return "<b>" + match.ToString() + "</b>"; 
      } 

      return ""; //no match 
     } 

그러나 때 단어 "대회"텍스트와 키워드 "투어"는 <b>tour</b>nament됩니다이다 : 그것은 더이 코드에 문제가 없다. 나는 완전한 단어를 강조하기 위해 그것을 원한다 : <b>tournament</b>.

어떻게하면됩니까?

답변

1

각 키워드 앞뒤에 \w*을 추가 할 수 있습니다. 이렇게하면 전체 단어가 키워드를 포함하면 일치합니다.

편집 : 코드에서,

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

그것을해야한다.

+0

코드에 나를 보여줄 수 있습니까? – Philip

+0

내가 할 수있는 .. 편집 =) – Jens

+0

매력처럼 작동! 감사! – Philip

관련 문제