Friday, August 16, 2013

Convert web addresses contained in a string to hyperlinks using a regular expression

In the event you ever need to convert web addresses contained within a string to hyperlinks, I stumbled across some code on StackOverflow that will allow you to do this via a regular expression.  The code for this solution is presented as follows:


private string ConvertUrlsToLinks(string msg) 
{
    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    Regex r = new Regex(regex, RegexOptions.IgnoreCase);
    return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

Special thanks goes to a user by the name of "Rob" on StackOverflow for providing this solution to the problem!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.