C#中搜尋關鍵詞高亮顯示

來源:互聯網
上載者:User

在搜尋關鍵詞高亮中一般的方法都是採用替換的辦法(Replace)這個方法有一個缺點就是不能區分大小寫問題。在網上找了找發現有人用Regex的方法來解決這個問題還真不錯,效率也比較高,歸納如下,有用得到的朋友可以一試。

        //搜尋關鍵詞高亮顯示函數         public static string HighLightKeyWord(string  pain,string keyword)         {

            //搜尋關鍵詞高亮函數By JN 2006.11.30              System.Text.RegularExpressions.MatchCollection m = Regex.Matches(pain, keyword,  RegexOptions.IgnoreCase);             //忽略大小寫搜尋字串中的關鍵字             for  (int j = 0; j < m.Count; j++)//迴圈在匹配的子串前後插東東              {                 //j×31為插入html標籤使pain字串增加的長度:                 pain =  pain.Insert((m[j].Index + keyword.Length + j * 31),  "</font>");//關鍵字後插入html標籤                 pain =  pain.Insert((m[j].Index + j * 31), "<font  color=#ff0000>");//關鍵字前插入html標籤             }

            //搜尋關鍵詞高亮函數By JN 2006.11.30             return  pain;         }

當然用之前引用先:using System.Web.UI.HtmlControls;

還有:using System.Text.RegularExpressions;(小魚加)

以上代碼有問題:同一句中有多個關鍵字時出問題

試一下這個先

/// <summary>         /// 替換關鍵字為紅色         ///  </summary>         /// <param  name="keycontent">原始內容</param>         /// <param  name="k">關鍵字,支援多關鍵字</param>         ///  <returns>String</returns>         /// <author>haver  Guo</author>         public static string Highlightkeywords(string  keycontent, string k)         {             string resultstr =  keycontent;             if (k.Trim().IndexOf(' ') >  0)             {                 string[] myArray = k.Split('  ');                 for (int i = 0; i < myArray.Length;  i++)                 {                     resultstr =  resultstr.Replace(myArray[i].ToString(), "<font color=#FF0000>" +  myArray[i].ToString() +  "</font>");                 }                 return  resultstr;             }             else             {                 return  resultstr.Replace(k, "<font color=#FF0000>" + k +  "</font>");             }         } 經測,可用

 

      public static string red(string theField, string fkeywords)
       
{
            string red;
            red = theField.Replace(fkeywords,
"<font color=\"red\">" + fkeywords + "</font>");
           
return red;
        }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.