.NET: Using a Regular Expression To Make a Link

If you saw the post last week on using the tweetsharp Twitter library for .NET, you saw a sample of the output for our quick little test. If you revist the output of the code, you will notice that the Twitter API will return plain text only, meaning the links contained in a tweet are just text. Thus they have no HTML code in them to make them a functional link. To solve this problem you can use a regular expression to find our link text and place it within a HTML link tag. After running a quick Google search, I came across a very good blog post at mikesdotnetting.com that covers some advanced regular expressions for C#. One of these samples includes an expression that will search for http, ftp and mailto text and converts it into functioning HTML. I used his code as is, with one exception. I preferred to have the links in my text open in a new window, so I added in the target tag to accomplish this.

<code lang="csharp[lines]">using System;<br></br>  
using System.Collections.Generic;<br></br>  
using System.Linq;<br></br>  
using System.Web;<br></br>  
using System.Text.RegularExpressions;```

///

<summary></summary><summary></summary>/// Summary description for Global  
 ///

<summary></summary><summary></summary>public class Global  
 {  
 public static string ReplaceLinks(string arg)  
 //Replaces web and email addresses in text with hyperlinks  
 {  
 Regex urlregex = new Regex(@"(^|[n ])((www|ftp).[^ ,""s String.Format(" [{1}]() ",  
 m.Groups[2].Value,  
 m.Groups[2].Value.Length > 27 ? m.Groups[2].Value.Substring(0, 27) + "..." : m.Groups[2].Value));

 Regex httpurlregex = new Regex(@"(^|[n ])((http://www.|http://|https://)[^ ,""s String.Format(" [{1}]() ",  
 m.Groups[2].Value,  
 m.Groups[2].Value.Length > 27 ? m.Groups[2].Value.Substring(0, 27) + "..." : m.Groups[2].Value));

 Regex emailregex = new Regex(@"([w_.-]+@[w_.-]+.w+s)");  
 arg = emailregex.Replace(arg,  
 m => String.Format(" [{1}]() ",  
 m.Groups[1].Value,  
 m.Groups[1].Value.Length > 27 ? m.Groups[1].Value.Substring(0, 27) + "..." : m.Groups[1].Value));

 return arg;  
 }  
 }

One quick note about that code above. To promote some code resuse I have created a class file called Global , where I created the function that houses our regular expression code. This class file goes into the App_Code folder, which then allows it to be called anywhere throughout our application. We can keep adding functions to this file as we build out our application. Calling the code is simple:

string x = Convert.ToString(yourvariablename);


x = Global.ReplaceLinks(x);```

Comments

comments powered by Disqus