Detect and Replace URLs in Text using Regex
Posted by Tihomir Ivanov on 24 November 2009 16:13
Rating: 0.00
Here's a simple example how you can detect URLs in some text and replace them with html code for hyperlinks:
string someText = "here's a simple text that contains urls in it like http://www.aspnetsource.com or http://aspnetsource.com or http://aspnetsource.com";
// we create a Regex object with pattern to detect URLs
Regex reg = new Regex(@"((http|https|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))*[\w\d:#@%/;$()~_?\+-=\\\.&]*)");
string htmText = reg.Replace(someText, "<a href=\"$1\">$1</a>");
/* now htmlText contains formatted html code with hrefs:
here's a simple text that contains urls in it like <a href="http://www.aspnetsource.com">http://www.aspnetsource.com</a> or <a href="http://aspnetsource.com">http://aspnetsource.com</a> or <a href="http://aspnetsource.com">http://aspnetsource.com</a>
*/
Comments:
No comments yet.