We need here some regular expression magic. First we find the emails. I hope we need not to validate them, so any word without spaces with @ followed by . is ok.
public static string MakeEmailsClickable( string input ){
if (string.IsNullOrEmpty(input) ) return input;
Regex emailFinder = new Regex(@"[^\s]+@[^\s\.]+.[^\s]+", RegexOptions.IgnoreCase);
return emailFinder.Replace(input, "<a href=\"mailto:$&\">$&</a>" );
}
$&
- represents the current match in regex.
To find Urls we asume that they start with some protocol name followed by ://
, again no spaces are allowed in it.
public static string MakeUrlsClickable( string input ){
if (string.IsNullOrEmpty(input) ) return input;
Regex urlFinder = new Regex(@"(ftp|http(s)?)://[^\s]*", RegexOptions.IgnoreCase);
return urlFinder.Replace(input, "<a href=\"$&\">$&</a>" );
}
This one looks for ftp, http or https links, but you can add any protocol into regex separating it with |
(pipe) like that: (file|telnet|ftp|http(s)?)://[^\s]*)
.
Actually URL may also have @ in it http://username:password@host:port/
, but I hope this is not the case, as then we will have to use some more strict regular expressions.