← back to articles

❯ cat converting-urls-into-links-with-regex.md

Converting URLs Into Links With Regex

1 min readtr#C##Convert#Regex
public static string WithActiveLinks(this string s)
{
  //Finds URLs with no protocol
  var urlregex = 
new Regex(@"b({0,1}(?<url>(www|ftp).[^ ,""s<)]*)b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  //Finds URLs with a protocol
  var httpurlregex = 
new Regex(@"b({0,1}(?<url>[^>]
(http://www.|http://|https://|ftp://)[^,""s<)]*)b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  //Finds email addresses
  var emailregex = 
new Regex(@"b(?<mail>[a-zA-Z_0-9.-]+@[a-zA-Z_0-9.-]+.w+)b", 
    RegexOptions.IgnoreCase | RegexOptions.Compiled);
  s = urlregex.Replace
(s, " <a href="http://${url}" target="_blank">${url}</a>");
  s = httpurlregex.Replace
(s, " <a href="${url}" target="_blank">${url}</a>");
  s = emailregex.Replace
  (s, "<a href="mailto:${mail}">${mail}</a>");
  return s;
}