Cybercrux

Everything is achievable through technology

Convert URL to Link


1.
///

/// Finds web and email addresses in a string and surrounds then with the appropriate HTML anchor tags
///

///
/// String
public static string WithActiveLinks(this string s)
{
//Finds URLs with no protocol
var urlregex = new Regex(@"\b\({0,1}(?(www|ftp)\.[^ ,""\s<)]*)\b",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
//Finds URLs with a protocol
var httpurlregex = new Regex(@"\b\({0,1}(?[^>](http://www\.|http://|https://|ftp://)[^,""\s<)]*)\b",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
//Finds email addresses
var emailregex = new Regex(@"\b(?[a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)\b",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
s = urlregex.Replace(s, " ${url}");
s = httpurlregex.Replace(s, " ${url}");
s = emailregex.Replace(s, "${mail}");
return s;
}
2.
string input = "[check out this URL!](http://www.reallycoolURL.com)";
string pattern = @"\[(?[^]]+)]\((?[^)]+)\)";//string pattern = @"\[([^]]+)]\(([^)]+)\)";
string replacement = @"${Text}";//string replacement = @"$1";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine(result);

3.
private string ConvertUrlsToLinks(string msg) {
string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s