Monday, May 18, 2009

Url Fetching from content and making "clickable" using Regular Expressions in .net

Here's a quite and easy way to find a url and surround it with anchor tags, and also putting a target='_blank' so that you could open up the link in a new tab. Very useful and powerful feature of Regex.

string yourtext = "Heres the link to the site: http://www.yoursite.com/content.html"

yourtext = Regex.Replace(yourtext, @"(http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?)", "<a target='_blank' href='$1'>$1</a>");

Now the text would look like:

Heres the link to the site: <a target='_blank' href='http://www.yoursite.com/content.html'>http://www.yoursite.com/content.html</a>

Regex Rocks!

No comments: