Auto-Link Using Regular Expressions

Auto-LinkingI was recently asked if I could automatically turn website text (ex: ) into HTML hyperlinks.  My first thought was ah CRAP!  I also wondered why they could not use the link tool in the editor, but they asked so I delivered. With about 5 minutes on Google, I found the perfect solution that worked for me.

Mind you I was working in C# for this, but since it is a regular expression solution; it will apply to virtually any language.  The one change that I had made from the original code was to add in a piece that also auto-linked when the text included “http://www.”.  You may or may not want the extra addition that I had made.

Original Article:

 public static string ActivateLinksInText(string source)  
     source = " " + source + " ";  
     // easier to convert BR's to something more neutral for now.  
     source = Regex.Replace(source, "<br>|<br />|<br/>", "\n");  
     source = Regex.Replace(source, @"([\s])(www\..*?|http://.*?)([\s])", "$1<a href=\"$2\" target=\"_blank\">$2</a>$3");  
     source = Regex.Replace(source, @"([\s])(http://www\..*?)([\s])", "$1<a href=\"$2\" target=\"_blank\">$2</a>$3");  
     source = Regex.Replace(source, @"href=""www\.", "href=\"http://www.");  
     //source = Regex.Replace(source, "\n", "<br />");  
     return source.Trim();  

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at:

Posted in C#, C-Sharp, Developement, How To, Web Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *