需求是这样的:有一段文本,里面可能包含一个或者多个链接的html.
现在需要修改成这样:如果链接不带target属性,则添加target='_blank';如果target属性是其他,则设置为target='_blank'
求实现代码,小弟谢过了。
------解决方案--------------------------------------------------------
test
- C# code
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>*/