LDNDeveloper

Andrew Pallant

Software & Web Developer


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




Auto-Link Using Regular Expressions

Physical Link: Auto-Link Using Regular Expressions


Auto-LinkingI was recently asked if I could automatically turn website text (ex: www.google.com ) 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: http://stackoverflow.com/questions/3037623/automatically-hyper-link-urls-and-emails-using-c-whilst-leaving-bespoke-tags

 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();  
   }  

The post Auto-Link Using Regular Expressions appeared first on Software Developer In London.

Author:
Categories: C#, C-Sharp, Developement, How To, Web, c#, DotNet, RegEx, Regular Expressions


Google | humanstxt.org | Andrew Pallant's Blog Site
©2017 LdnDeveloper