Tuesday, December 8, 2009

convert url to links in C# using Regex

public string ConvertUrlsToLinks(string msg)
{
string newMsg = "";

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

string emailRegex = @"(([a-zA-Z0-9_\-\.]+@)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r2 = new Regex(emailRegex, RegexOptions.IgnoreCase);
newMsg = r2.Replace(newMsg, "$1");

return newMsg;
}

No comments: