• C#中搜索关键词高亮显示


    在搜索关键词高亮中一般的方法都是采用替换的办法(Replace)这个方法有一个缺点就是不能区分大小写的问题。在网上找了找发现有人用正则表达式的方法来解决这个问题还真不错,效率也比较高,归纳如下,有用得到的朋友可以一试。

            //搜索关键词高亮显示函数         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;
            }

  • 相关阅读:
    自用python时间格式转换lib库代码
    如何在datetime.strptime中添加时区
    bs3迁移到bs4, import lxml.html.soupparser 报错的解决
    mac下pip install lxml报错
    删除 Mac OS 10.10 中“打开方式”里重复或无用的程序列表
    python的urllib2库详细使用说明
    近期个人项目计划
    在centos中添加freeswitch服务开机自动运行
    ddd
    Sqlserver 2008安装
  • 原文地址:https://www.cnblogs.com/cuihongyu3503319/p/2861875.html
Copyright © 2020-2023  润新知