显示时将部分字符串转换为URL

时间:2012-09-24 15:21:58

标签: asp.net-mvc razor

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

  

我喜欢网站http://somesitehere.com/somepage.html,我建议您也尝试一下。

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

@Model.MyText

即使StackOverflow也能获得它。

3 个答案:

答案 0 :(得分:1)

一种方法是在一大块文本上进行正则表达式匹配,并用锚标记替换该url字符串。

答案 1 :(得分: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; 
}

答案 2 :(得分:1)

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

  ?

的https:// +([A-ZA-Z0-9 \〜\ @#\ $ \%\ ^ \&安培; *()_- \ =(\ W + \ W +?。])! + \ / \:??\; \'\,] *)

.net字符串表示:

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