【问题标题】:Use Regex to replace HREFs使用 Regex 替换 HREF
【发布时间】:2011-03-11 09:03:02
【问题描述】:

我有想要跟踪点击活动的 html 电子邮件。我需要更新电子邮件中的所有 href 以指向我的服务器,在那里它们可以被记录和重定向。有没有一种简单的方法可以使用 .Net 正则表达式在全球范围内做到这一点?

<a href="http://abc.com">ABC</a>

变成

<a href="http://mydomain.com?uid=123&url=http:/abc.com>ABC</a>

【问题讨论】:

  • 电子邮件数据是由某人从表单域生成的吗?所以你想在他们将数据发布到服务器后更改它?

标签: .net regex replace href


【解决方案1】:

不要使用 RegEx 来解析 HTML - 它不是常规语言。请参阅here 了解一些引人注目的演示。

使用 HTML Agility Pack 解析 HTML 并替换 URL。

【讨论】:

    【解决方案2】:

    试试下面的代码

    public string ReplaceLinks(string emailSource) {
        string resultString = null;
        try {
            resultString = Regex.Replace(emailSource, "(<a href=\")(htt)", new MatchEvaluator(ComputeReplacement));
        } catch (ArgumentException ex) {
            // Syntax error in the regular expression
        }
        return resultString;
    }
    
    public String ComputeReplacement(Match m) {
        // You can vary the replacement text for each match on-the-fly
        return "$1http://mydomain.com?uid=123&url=$2";
    }
    

    【讨论】:

    • 我不明白为什么@Oded 的解决方案不被接受,它不仅更清晰而且更有意义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    相关资源
    最近更新 更多