之前我在C#版刚好发了100个贴子。虽然已是身经百问,但仍菜鸟一个。刚刚又被正则表达式卡住了,不同的是以前上来直接问人要,这次我自己写了个式子,不能用,请大家看错在哪里。目标字符串(从html源码中截取的)
<body bgcolor=#ffffff topmargin=0 leftmargin=0 text="#000000" background="/shop/image/x-background.gif" link="#006600" vlink="#006600"><td align="center" background="/shop/image/bg3.gif" height="20">上面background后面都是相对路径,我要把它转换成绝对路径:
            string sHtml;
            Uri baseUri;
            ...             Regex bg = new Regex("background=\"(<local>.*?)\"");
            MatchCollection mc = bg.Matches(sHtml);
            foreach (Match m in mc)
            {
                sHtml = sHtml.Replace(m.Value, "background=\"" + makeAbsoluteURL(baseUri, m.Groups["local"].Value+"\""));
            }
结果没有能够捕获,请问我的正则表达式需要做何修改?

解决方案 »

  1.   


             static void Main(string[] args)
            {
                string str = @"<body bgcolor=#ffffff topmargin=0 leftmargin=0 text=""#000000"" background=""/shop/image/x-background.gif"" link=""#006600"" vlink=""#006600"">";
                string sHtml = Regex.Replace(str, @"(?i)(?<=background="")[^""]*", new MatchEvaluator(RegexReplace));
                Console.WriteLine(f);
                Console.ReadLine();
            }
            private static string RegexReplace(Match m)
            {
                return makeAbsoluteURL(baseUri, m.Value);
            }
    注意Regex.Replace的重载还有 命名组是 (?<name>exp) 
    你少了个问号
      

  2.   

    果然是少了个问号。我用Regex bg = new Regex("background=\"(?<local>.*?)\"");获得了成功,这个式子要比楼上朋友的简单,楼上朋友的式子是如何考虑的呢?
      

  3.   

    正则不是楼主那样用的,不需要先匹配出来再替换,直接替换就是了楼主使用的方式和正则本身都效率比较低
    string test = @"<body bgcolor=#ffffff topmargin=0 leftmargin=0 text=""#000000"" background=""/shop/image/x-background.gif"" link=""#006600"" vlink=""#006600""> ";
    Regex reg = new Regex(@"(?<=background="")(?=[^""]+"")");
    string result = reg.Replace(test, "http://www.test.com");
      

  4.   

    直接找到background后面的[^""]*替换就是了