zoukankan      html  css  js  c++  java
  • 用正则表达式做内容关键字链接

     

     private void rc()
        {
            string str1 = "<img src=\"sss.jpg\" alt=\"网络技术网络;网络应用\">网络技术网络;网络应用 网络基本知识 <img src=\"sss.jpg\" alt=\"网络技术网络;网络应用\"><a  href=\"http://www.stobar.cn/">网络技术网络;网络应用 网络基本知识</a>";

     List<string> keys = new List<string>();
            keys.Add("网络");
            keys.Add("网络技术");
            keys.Add("网络基本");
            string result = keyAddUrl(str1, keys,"http://www.baidu.com/");
            this.Label1.Text = result;

        }

        /// <summary>
        /// 给关键字加链接,同一关键字只加一次
        /// </summary>
        /// <param name="src">源字符串</param>
        /// <param name="keys">关键字泛型</param>
        /// <param name="keys">链接地址</param>
        /// <returns>替换后结果</returns>
        private string keyAddUrl(string src, List<string> keys ,string URL)
        {
            Regex reg = new Regex(@"(?i)(?:^|(?<!<a\b(?>[^<>]*))>)(?>[^<>]*)(?:<|$)");
            int length = 0;
            string temp = string.Empty;
            return reg.Replace(src, delegate(Match m)
            {
                temp = m.Value;
                length = temp.Length;
                for (int i = keys.Count - 1; i >= 0; i--)
                {
                    temp = Regex.Replace(temp, @"(?is)^((?:(?:(?!" + Regex.Escape(keys[i]) + @"|</?a\b).)*<a\b(?:(?!</?a\b).)*</a>)*(?:(?!" + Regex.Escape(keys[i]) + @"|</?a\b).)*)(?<tag>" + Regex.Escape(keys[i]) + @")", @"$1<a href="+URL+" target=\"_blank\" title=\"${tag}\">${tag}</a>");
                    if (length != temp.Length)
                    {
                        keys.Remove(keys[i]);
                    }
                    length = temp.Length;
                }
                return temp;
            });
        }

  • 相关阅读:
    delete误删除恢复
    oracle自增字段
    oracle唯一约束
    linux得到系统当前日期
    to_char+fm
    oracle范围分区
    oracle之use_hash用法
    oracle11g的regexp函数
    第一个脚本输入参数
    使用ctl将txt或csv文件导入表数据
  • 原文地址:https://www.cnblogs.com/dfsxh/p/1782073.html
Copyright © 2011-2022 走看看