2

我四处寻找解决方案,我确信这是一个简单的问题,但仍然不确定如何做到这一点。所以,我有一个包含很多单词的字符串,有时它里面有链接。例如:

我喜欢这个网站http://somesitehere.com/somepage.html,我建议你也试试。

我想在我的视图中显示字符串并将所有链接自动转换为 URL。

@Model.MyText

甚至 StackOverflow 也能得到它。

4

3 回答 3

1

一种方法是对一段文本进行正则表达式匹配,然后用锚标记替换该 url 字符串。

于 2012-09-24T15:24:02.393 回答
1

@Hunter 是对的。此外,我在 C# 中找到了完整的实现:http ://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link .aspx

万一原始链接失效

VB.Net 实现

Protected Function MakeLink(ByVal txt As String) As String
    Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)

    Dim mactches As MatchCollection = regx.Matches(txt)

    For Each match As Match In mactches
        txt = txt.Replace(match.Value, "<a href='" & match.Value & "'>" & match.Value & "</a>")
    Next

    Return txt
End Function

C#.Net 实现

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; 
}
于 2012-09-24T15:32:06.160 回答
1

另一个可以与 KvanTTT 答案一起使用的正则表达式,并且具有接受 https url 的额外好处

https?://([\w+?.\w+])+([a-zA-Z0-9\~!\@#\$\%\^\&*()_-\=+\/\ ?.:\;\'\,]*)?

.net 字符串表示:

"https?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?"
于 2016-02-09T09:08:50.023 回答