Sep 12
Converting a URL into a Link in C# Using Regular Expressions
I added the Twitter updates to the site and then realized that the URL's in the tweets come as plain text and not as <a /> links. So I created a function to detect URLs in a given string and convert them into links. It uses a regular expression for the URL detection...
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, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"_blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
}
blog comments powered by Disqus