之前我在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+"\""));
}
结果没有能够捕获,请问我的正则表达式需要做何修改?
<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+"\""));
}
结果没有能够捕获,请问我的正则表达式需要做何修改?
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)
你少了个问号
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");