Sep 12

Converting a URL into a Link in C# Using Regular Expressions

A C# code snippet that detects URLs and coverts them to links.

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)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
        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=\"&#95;blank\">$1</a>").Replace("href=\"www", "href=\"http://www");

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top