2010-07-03 64 views
1

我有我想跟蹤點擊活動的HTML電子郵件。我需要更新電子郵件中的所有hrefs,以指向我的服務器,在那裏他們可以被記錄和重定向。有一種簡單的方法來使用.Net正則表達式在全球範圍內執行此操作嗎?使用正則表達式來替換HREF

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

成爲

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

正在從一個表單域的人所產生的電子郵件數據?所以你想在將數據發佈到服務器後進行更改? – spinon 2010-07-03 06:35:27

回答

-1

嘗試下面的代碼

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"; 
} 
+0

經過微小的修改,它工作得很好。謝謝。 – Lauren 2010-07-04 16:43:43

+0

我不明白爲什麼@Oded的解決方案不是公認的解決方案,它不僅更清晰,而且更有意義 – 2013-03-12 21:41:08

2

不要使用正則表達式來解析HTML - 它不是一個正規語言。參見here進行一些引人注目的演示。使用HTML Agility Pack解析HTML並替換URL。