Search code examples
c#asp.netregexlinkify

C# code to linkify urls in a string


Does anyone have any good c# code (and regular expressions) that will parse a string and "linkify" any urls that may be in the string?


Solution

  • It's a pretty simple task you can acheive it with Regex and a ready-to-go regular expression from:

    Something like:

    var html = Regex.Replace(html, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
                             "\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
                             "([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
                             "<a href=\"$1\">$1</a>");
    

    You may also be interested not only in creating links but in shortening URLs. Here is a good article on this subject:

    See also: