大家好,本人想做个给关键字加链接的功能!在发布时,将指定关键字加链接  如“和尚” 变成 <a href=''>和尚</a>
 于是想到了用 str.replace("和尚","<a href=''>和尚</a>") 在发布时,这样做是可以的,但是发布完了想修改时就会出现再次被替换的情况 。 "和尚" 会被变成 <a href=''><a href=''>和尚</a></a>. 于是想到一个方法,想用正则表达式将指定关键字(可以为多个)的链接先替换掉,如 <a href=''>和尚</a> 还原为 "和尚". 这样再次修改的时候,就不会出现这种情况了。特来请教大家,此正则怎么写?

解决方案 »

  1.   

                Regex.Replace(s, @"<\/a>|<a.*?>", "")
      

  2.   

    if(!str.StartWith("和尚"))
      str.Replace("和尚"," <a href=''>和尚 </a>");
      

  3.   

    把这些都学会了 我相信  你自己写应该没问题了
    http://tech.ddvip.com/2009-05/1242879926120281.html(正则表达式)
      

  4.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication1
    {
        class Test
        {
            static void Main()
            {
                string[] str = new string[] { @"<a href=''>和尚 </a>", @"<a href=''>xxxxx</a>" };
                Regex re = new Regex(@"<a[^>]*>(?<TK>[^<]*)</a>");
                foreach (string s in str)
                {
                    if (re.Match(s).Success)
                        Console.WriteLine(re.Match(s).Groups["TK"].Value);            }        }
        }
    }
      

  5.   


    "<a[^>]*>[^<]*</a>";//匹配 <a href=''> 和尚 </a> 
    "(?<=<a[^>]*>)[^<]*(?=</a>)";//匹配<a href=''> 和尚 </a> 中的 和尚
      

  6.   

    除非你想替换为不同的链接,否则没必要那样做,直接替换就是了string test = "如 <a href=''>和尚 </a> 还原为 和尚. ";
    Regex reg = new Regex(@"(?<!<a[^>]*>)和尚(?!</a>)");
    string result = reg.Replace(test, "<a href=''>和尚</a>");