2014-12-06 83 views
1

我在使用LinqToTwitter API的twitter API。我正在嘗試格式化tweet文字。但是我有一個問題,更換和下面的正則表達式是我從Twitter替換和RegEx問題

@TheNational: ICYMI: Louvre be first museum in Asia to show a painting http://t.co/fmp http://t.c…

讓我現在用下面的代碼替換所有的URL鏈接,顯示的字符串。

首先,我創建正則表達式來獲取鏈接

private readonly Regex _parseUrls = new Regex("(?<Protocol>\\w+):\\/\\/(?<Domain>[\\[email protected]][\\w.:@]+)\\/?[\\w\\.?=%&=\\[email protected]/$,]*", RegexOptions.IgnoreCase | RegexOptions.Compiled); 

然後,我與它們匹配和替換如下

foreach (var urlMatch in _parseUrls.Matches(tweetText)) 
    { 
    Match match = (Match)urlMatch; 
    tweetText = tweetText.Replace(match.Value, string.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value)); 
    } 

正則表達式按預期工作非常好,但現在取而代之的是給問題,因爲在這兩個環節字符串以http://t.co開頭,每次都替換第一次出現。

有人幫助我,我失蹤了。

回答

1

這不是一個正確的方法來做替換。

使用Regex.Replace方法:

_parseUrls.Replace(tweetText, "<a href=\"$&\" target=\"_blank\">$&</a>"); 

或者,更好的是,與HTML編碼:

_parseUrls.Replace(tweetText, 
        match => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", 
              match.Value, 
              WebUtility.HtmlEncode(match.Value)) 
       ); 

這將爲例如把任何&在URL中&amp;<a>標籤內。你甚至應該對字符串的其餘部分進行編碼:如果有人推送了一些HTML代碼,你希望按原樣顯示它,而不是解釋它。

與原有方法的問題是,_parseUrls.Matches(tweetText)替換文本再次每次迭代匹配。

+0

你解決了我的大問題非常感謝你 – Milind 2014-12-06 14:59:41