C#替换锚文本

时间:2013-04-10 11:36:38

标签: c# regex replace anchor

输入到我们数据库的一些链接是巨大的,我需要控制它,因为它正在破坏报告。

我需要以编程方式转换:

<a href="http://www.thisismylongurl.com">http://www.thisismylongurl.com</a>

<a href="http://www.thisismylongurl.com">Link</a>

我已经研究过Regex.Replace,但似乎无法找到一个能够满足我需要的产品。

如果不明显,“http://www.thisismylongurl.com”每次都会是一个不同的网址,所以我需要使用正则表达式而不是固定的字符串替换。

2 个答案:

答案 0 :(得分:0)

当替换中的“链接”没有改变时,你可以尝试这个

(<\s*a\s+href="[^"]+">)[^<]*(?=</a>)

并替换为

$1Link

here on Regexr

\s匹配空格字符

[^"]是一个否定的字符类,匹配除"

之外的任何字符

(?=</a>)是一个积极的前瞻性插入,可确保</a>跟随匹配。

$1为您提供第一个捕获组的内容,即第一个左括号后面的子模式匹配的内容。

答案 1 :(得分:0)

完美的作品。没有正则表达式参与。

  protected void Page_Load(object sender, EventArgs e)
    {

        string str1="<a href='http://www.thisismylongurl.com'>http://www.thisismylongurl.com</a>";
        int b1 = str1.IndexOf(">");
        int b2 = str1.LastIndexOf("<");
        str1= str1.Remove(b1+1);
        int b3 = str1.IndexOf(">");
        str1 = str1.Insert(b3+1, "Link");
        Response.Write(str1);
    }