Quantcast Tìm Url trong text và mark chúng as Link

Tìm Url trong text và mark chúng as Link

by Neon Quach 24. May 2010 17:58

Cho rằng bạn có 1 chuổi text, và bạn muốn tìm các địa chỉ url trong chuổi đó có đánh dấu chúng thành tag link. Nay mình cung cấp cho các bạn 1 phương thức để làm việc này.

Đâu tiên, chúng ta phải tìm ra tất các url trong text đó, sau đó chúng ta sẻ gắn tag <a> cho url đó.
Đây là pattern mà nó match với url:
-------- In VB.Net ---------

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

-------- In C#.Net ---------
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

Phương thức sau chuyển Url thành liên kết.
-------- In VB.Net ---------
Protected Function MakeLink(ByVal txt As String) As String
        Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&amp;\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", 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

------- In C#.Net --------
protected string MakeLink(string txt)
{"font-family: verdana,geneva;">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;
}

Regards,
Thank farazshahkhan for your method,

Tags: , ,


Categories: vs .net | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers