如何使用regexp突出显示带关键字的完整单词?

问题描述:

我有更长的文字和一些关键字。我想在我的文本中突出显示这些关键字。与此代码没有问题:如何使用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>

我该怎么做?

您可以在每个关键字前后添加一个\w*。这样,如果整个单词包含关键字,它就会匹配。

编辑:在你的代码,

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

应该这样做。

+0

你可以在代码中显示我吗? – Philip 2010-02-26 07:55:13

+0

我可以..编辑=) – Jens 2010-02-26 08:06:41

+0

工程就像一个魅力!谢谢! – Philip 2010-02-26 08:09:53