Regex to find URL within text and make them as link

Some time back on the form somebody was looking for some help in searching URL within text and make those URLs as link. Me and that guy tried various regex but the one that worked out I thought to put it on the blog so that it can help me and others later. Regex itself is:

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

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

And I used following method to convert the URLs into link within text.

-------- In 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

------- In 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;
}

31 Comments

Comments have been disabled for this content.