日期:2014-05-17  浏览次数:20521 次

网址的正则表达式替换
原网址: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");