读书人

因特网址的正则表达式替换

发布时间: 2012-10-25 10:58:58 作者: rapoo

网址的正则表达式替换
原网址:href="/Product/List-0039,0084.shtml"

转换为目标网址:href="http://abc.sina.com.cn/Product/List-0039,0084.shtml"

求解!也就是说要把网页内部的所有网址,没有带上域名的,全部要在里面加上域名进行访问。

[解决办法]

C# code
            string source = @"href=""/Product/List-0039,0084.shtml""";            Regex reg = new Regex(@"(?is)(?<=href="")/[^""]+(?="")");            source = reg.Replace(source, @"http://abc.sina.com.cn$0");            MessageBox.Show(source);
[解决办法]
正则没问题,你我自己使用的问题
你代码里的双引号转义了么?

Regex reg = new Regex(@"(?i)href=(['"]?)(?=(?!https?://)[^'"\s]+\.(?:shtml|css|js|aspx)\1)");
==============
Regex reg = new Regex(@"(?i)href=(['""]?)(?=(?!https?://)[^'""\s]+\.(?:shtml|css|js|aspx)\1)");



source = reg.Replace(source, @"http://abc.sina.com.cn$0");
========
source = reg.Replace(source, @"$0http://abc.sina.com.cn");

最终正确代码:

C# code
  Regex reg = new Regex(@"(?i)href=(['""]?)(?=(?!https?://)[^'""\s]+\.(?:shtml|css|js|aspx)\1)");  source = reg.Replace(source, @"$0http://abc.sina.com.cn"); 

读书人网 >asp.net

热点推荐