日期:2014-05-18 浏览次数:20454 次
string str = @"<a href=""http:www.csdn.net"" target=""_blank"">csdn</a> <a href=""http:www.csdn.net"">csdn</a> <a href=""http:www.csdn.net"" target=""csdn"">csdn</a> <a href=""http:www.csdn.net"" target=""baidu"">csdn</a> <a target=""baidu"" href=""http:www.csdn.net"">csdn</a> <a target=""_blank"" href=""http:www.csdn.net"">csdn</a> <a href=""http:www.csdn.net"" target=""_blank"">csdn</a>"; Regex reg = new Regex(@"(?is)(?<=<a\b)(?:((?:(?!target)[^>])*)>|[^>]*?target=""(?!_blank)[^'""\s]+""[^>]*?>)"); string result = reg.Replace(str, delegate(Match m) { if (m.Groups[1].Success) return m.Groups[1].Value + @" target=""_blank"""; else return Regex.Replace(m.Value, @"(?<=target="")[^""]+(?="")", "_blank"); }); Console.WriteLine(result); /* <a href="http:www.csdn.net" target="_blank">csdn</a> <a href="http:www.csdn.net" target="_blank"csdn</a> <a href="http:www.csdn.net" target="_blank">csdn</a> <a href="http:www.csdn.net" target="_blank">csdn</a> <a target="_blank" href="http:www.csdn.net">csdn</a> <a target="_blank" href="http:www.csdn.net">csdn</a> <a href="http:www.csdn.net" target="_blank">csdn</a> */