Converting URLs Into Links With Regex

Following on from the recent spate of extensions methods I've posted, here's another I use to convert URLs and email addresses into links within HTML. You may want to restrict users from submitting HTML tags via forms in your application, which means that URLs and email addresses that they submit appear as plain text unless they are subjected to some kind of processing.


/// <summary>
/// Finds web and email addresses in a string and surrounds then with the appropriate HTML anchor tags 
/// </summary>
/// <param name="s"></param>
/// <returns>String</returns>
public static string WithActiveLinks(this string s)
{
  //Finds URLs with no protocol
  var urlregex = new Regex(@"\b\({0,1}(?<url>(www|ftp)\.[^ ,""\s<)]*)\b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  //Finds URLs with a protocol
  var httpurlregex = new Regex(@"\b\({0,1}(?<url>[^>](http://www\.|http://|https://|ftp://)[^,""\s<)]*)\b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  //Finds email addresses
  var emailregex = new Regex(@"\b(?<mail>[a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)\b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  s = urlregex.Replace(s, " <a href=\"http://${url}\" target=\"_blank\">${url}</a>");
  s = httpurlregex.Replace(s, " <a href=\"${url}\" target=\"_blank\">${url}</a>");
  s = emailregex.Replace(s, "<a href=\"mailto:${mail}\">${mail}</a>");
  return s;
}

This will convert most URLs, but not all. Parsing URLs is not the easiest thing to do so you need to make a judgement on what type of URLs your users/visitors are most likely to provide and alter the regex patterns accordingly. One thing to point out is that the second pattern (the one that matches URLs with a protocol - http, https etc) also checks to make sure that it isn't already a hyperlink. By the time the second Replace() operations takes place, URLs without protocols will already be fitted with them, and have HTML surrounding them.

 

Date Posted:
Last Updated:
Posted by:
Total Views to date: 11901

1 Comment

- Tvrtko

Hello Mike,
this works great, however, part with email link will duplicate anchor tag. For http urls you did ignore existing html anchors from match correctly , but for email they get matched even if they have html anchor around already.

Recent Comments

Gayan 7/3/2015 6:20 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Great Article thanks...

Semil 7/1/2015 7:03 AM
In response to iTextSharp - Drawing shapes and Graphics
I have created a rectangle using above methode. Now I want to add a text in the center of this How I...

Satyabrata Mohapatra 6/30/2015 6:12 PM
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Ahh.....this is awesome. Happy to see after a long time you wrote a article on web form :D...

Marty 6/30/2015 7:16 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, you're the Man! Another great article. So incredibly helpful. I'm definitely going to buy your...

Rohan 6/30/2015 5:32 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Very good and helpful tutorial. Thanks. Just wanted to know what would be the max file size limit we...

Fernando 6/30/2015 1:59 AM
In response to Programmatically accessing data from DataSource controls
What if I want to pass parameters natively using the DataSourceSelectArguments object, instead of be...

pankaj 6/29/2015 3:13 PM
In response to How to retain carriage returns or line breaks in an ASP.NET web page
very nice i'm use this in my code thank you.... ...

Mike 6/29/2015 2:22 AM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
This is the first example that I have found that works....

Marty 6/28/2015 4:57 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, what if I don't want to render back the text to the browser, but I want to send it some other...

Mike 6/27/2015 4:00 PM
In response to Migrating Classic ASP To ASP.NET Razor Web Pages Part One- Razor Syntax And Visual Basic
have you used any of the code converters to convert classic asp to c#? If so, which one do you have...