---
title: "匹配html中的所有A标签并替换 "
author: "njmnjx"
date: "2011-06-25T09:30:55Z"
tags: []
categories: ["编程语言"]
slug: "html-a"
draft: false
lastmod: "2011-06-25T09:30:55Z"
id: 1104498
url: "https://njm.iteye.com/blog/1104498"
---

匹配html中的A标签

```regex
<[aa]\s+((\w+\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+))\s+)*)(href\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+)))((\s+\w+\s*=\s*("([^"]*)"|'([^']*)'|([^'">\s]+)))*)\s*>(.*?)</[aa]\s*>
```

替换其中的链接到统计页面再跳转到真正的链接地址
        
```C#

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>