日期:2014-05-17  浏览次数:20560 次

匹配html中的所有A标签并替换
匹配html中的A标签
<[aA]\s+((\w+\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+))\s+)*)(href\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+)))((\s+\w+\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+)))*)\s*>(.*?)</[aA]\s*>

替换其中的链接到统计页面再跳转到真正的链接地址
       
protected void Unnamed1_Click(object sender, EventArgs e)
    {
        //正则
        Regex reg = new Regex("<[aA]\\s+((\\w+\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^'\">\\s]+))\\s+)*)(href\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^'\">\\s]+)))((\\s+\\w+\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^'\">\\s]+)))*)\\s*>(.*?)</[aA]\\s*>");
        
        //输入内容
        string matchStr = TextBox1.Text;
 
        //此处可以完成任务(利用委托)
        MatchEvaluator myEvaluator = new MatchEvaluator(ReplaceCC);
        string aaa = reg.Replace(matchStr, myEvaluator);

        //最后结果
        Response.Write(aaa);
    }

//在这里单独处理每一个匹配项
    public string ReplaceCC(Match m)
    {
        string temp = m.Groups[9].Value + m.Groups[10].Value + m.Groups[11].Value;
        string g18 = m.Groups[18].Value;

        temp = "http://www.biaodashi.com?projectid=00000&userid=1111111&url=" + temp;

        return "<a " + m.Groups[1].Value + " href=\" " + temp + "\" " + m.Groups[12].Value + ">" + g18 + "</><br/>";
    }



实例:http://dl.iteye.com/topics/download/41e998cf-b147-3236-9c7e-c9573924b375