这是匹配超级连接的正则表达式:(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
上面的正则能够匹配所有超链接格式的字符串。我现在有个需求:不匹配a标签中的链接地址:
就是说,当<a href='http://www.baidu.com'></a>和http://www.google.com这两个连接在同一个字符串中的时候,只匹配http://www.google.com而不匹配http://www.baidu.com,这如何实现呢?

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication13
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str = "<a href='http://www.baidu.com'></a>和http://www.google.com";
                Regex rgx = new Regex(@"(?<!=['""=])(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?(?!=['""])");
                Console.Write(rgx.Match(str).Value);
            }
        }
    }
    限制链接左边不能为',"和=右边不能为'和"
      

  2.   

    Try:(?<!<a[^>]*?href=(['"\s]?))(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?
      

  3.   


    void Main()
    {
      string str = "<a href='http://www.baidu.com'></a>和http://www.google.com";
    Regex rgx = new Regex(@"(?<!<a[^>]*?href=(['""\s]?))(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");
    Console.Write(rgx.Match(str).Value);
                //http://www.google.com
    }