I am trying to come up with regexp and have tried many combinations and searches to find a solution for converting non hyperlinks to hyperlinks.
t
http:
I want the elements http://twitpic.com/abcdef , http://www.smh.com.au and www.hotmail.com be selected, but not http://www.aaaaaaaa.com , as they are already wrapped with a <a> tag.
I am currently using this regex in C #
return Regex.Replace(input, @"(\b((http|https)://|www\.)[^ ]+\b)", @" <a href=""$0"" target=""_blank"">$0</a>", RegexOptions.IgnoreCase);
I have no idea how to get him to exclude things already wrapped in <a> or <img>
Reference:)
EDIT
For those who read this later, this is the final solution I came up with
/// <summary> /// Adds to the input string a target=_blank in the hyperlinks /// </summary> public static string ConvertURLsToHyperlinks(string input) { if (!string.IsNullOrEmpty(input)) { var reg = new Regex(@"(?<!<\s*(?:a|img)\b[^<]*)(\b((http|https)://|www\.)[^ ]+\b)"); return reg.Replace(input, new MatchEvaluator(ConvertUrlsMatchDelegate)); } return input; } public static string ConvertUrlsMatchDelegate(Match m) { // add in additional http:// in front of the www. for the hyperlinks var additional = ""; if (m.Value.StartsWith("www.")) { additional = "http://"; } return "<a href=\"" + additional + m.Value + "\" target=\"_blank\">" + m.Value + "</a>"; }
source share