这是匹配超级连接的正则表达式:(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,这如何实现呢?
上面的正则能够匹配所有超链接格式的字符串。我现在有个需求:不匹配a标签中的链接地址:
就是说,当<a href='http://www.baidu.com'></a>和http://www.google.com这两个连接在同一个字符串中的时候,只匹配http://www.google.com而不匹配http://www.baidu.com,这如何实现呢?
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\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?(?!=['""])");
Console.Write(rgx.Match(str).Value);
}
}
}
限制链接左边不能为',"和=右边不能为'和"
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\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?");
Console.Write(rgx.Match(str).Value);
//http://www.google.com
}