/ Published in: C#
Will return a string that has any matched URLs wrapped in <a> tags.
Example: "This is a link to http://foobar.com . Please visit !"
Becomes: "This is a link to <a href='http://foobar.com'>http://foobar.com</a> . Please visit!"
Note: Opens links in new window.
Credit for regex: Faraz Shah Khan
Expand |
Embed | Plain Text
public static string FormatUrls(string input) { string output = input; Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase); MatchCollection mactches = regx.Matches(output); foreach (Match match in mactches) { output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>"); } return output; }
Comments
Subscribe to comments
You need to login to post a comment.

There is a small problem with this one.
Try inserting this:
This is a link to http://coalition.iforums.us/risca-vm2.html, please visit.
The comma sign will be considered part of the URL, while it is actually not.
@Vordreller: Thanks for catching that, guess that's what I get for grabbing the regex from someone else :) I'll have to update that after I test a few similar situations.
Updated regex, trying to get closer to w3c URI spec.
Last char must be either: letter,number, ?,#, =, /