2011-01-20 73 views
5

可能重複:
C# code to linkify urls in a string正則表達式的字符串中找到的網址

我敢肯定,這是一個愚蠢的問題,但我不能在任何地方找到一個體面的答案。我需要一個好的C#正則表達式。它需要找到一個字符串中的所有URL,以便我可以將每個URL包裝在html中以使其可點擊。

  1. 什麼是最好的表達使用這個?

  2. 一旦我有了表達式,用正確格式化的對應項替換這些URL的最佳方式是什麼?

在此先感謝!

+3

可能重複? [C#代碼來鏈接URL中的字符串](http://stackoverflow.com/questions/758135/c-code-to-linkify-urls-in-a-string) – eldarerathis 2011-01-20 16:51:59

回答

34

我現在用的這個權利:

text = Regex.Replace(text, 
       @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", 
       "<a target='_blank' href='$1'>$1</a>"); 
7

使用此代碼

protected string MakeLink(string txt) 
{ 
    Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);   
    MatchCollection mactches = regx.Matches(txt);   
    foreach (Match match in mactches) 
    { 
     txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>"); 
    }  
    return txt; 
} 
+1

使用`{}`按鈕,而不是````按鈕。:) – 2011-01-20 16:57:57

+0

使用`RegexOptions.Compiled`和`String.Format` – abatishchev 2011-01-20 16:57:57

相關問題