要实现的效果:让一段文本中所有超链接都在新窗口中打开。有些<a>没有定义target属性,则要用正则加进去,如果有target属性,但属性值不是_blank,也要改为_blank。

解决方案 »

  1.   


                string str = "<a class=\"zzz\">this is one</a><br/>"
                    + "<a class=\"zzz\" target=\"_self\">this is one</a><br/>"
                    + "<a class=\"zzz\" target=\"_blank\">this is one</a><br/>";
                string result = Regex.Replace(str, @"(?is)(?<=<a[^>]*)(target=['""\s]([^'""\s]+)['""\s])", delegate(Match m)
                {
                    if (m.Groups[2].Value == "_blank")
                        return m.Value;
                    else
                        return "target=\"_blank\"";
                });
                result = Regex.Replace(result, @"(?is)(<a(?![^>]*?target=['""][^'""]*?['""]))", "$1 target=\"_blank\"");
                Response.Write(result + "<br/>");
    /*
    <a target="_blank" class="zzz">this is one</a>
    <a class="zzz" target="_blank">this is one</a>
    <a class="zzz" target="_blank">this is one</a>
    */
      

  2.   

    调整下逻辑,一个正则就可以实现了string str = "<a class=\"zzz\">this is one</a>\n"
                 + "<a class=\"zzz\" target=\"_self\">this is one</a>\n"
                 + "<a class=\"zzz\" target=\"_blank\">this is one</a>\n";
    string result = Regex.Replace(str, @"(?is)(?<=<a(?:(?!\btarget\b)[^>])*)(?:\starget=(['""]?)((?:(?!\1).)*)\1(?=[^>]*>)|(?=>))", delegate(Match m)
    {
        if (m.Groups[2].Value == "_blank")
            return m.Value;
        else
        return " target=\"_blank\"";
    });
    richTextBox2.Text = result;
    /*------输出-------
    <a class="zzz" target="_blank">this is one</a>
    <a class="zzz" target="_blank">this is one</a>
    <a class="zzz" target="_blank">this is one</a>
    */
      

  3.   

    建议LZ到msdn 上 看下 Regex.Replace方法的介绍