Posted By

jasonseney on 03/19/09


Tagged

regex url c strings


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

cschlens
paelgr
umang_nine
mheinrich
Priestd09
danfinrud55


Format URLs in string to HTML Links in C#


 / 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

  1. public static string FormatUrls(string input) {
  2. string output = input;
  3. Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
  4.  
  5. MatchCollection mactches = regx.Matches(output);
  6.  
  7. foreach (Match match in mactches) {
  8. output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
  9. }
  10. return output;
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Vordreller on March 22, 2009

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.

Posted By: jasonseney on March 31, 2009

@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.

Posted By: jasonseney on April 14, 2009

Updated regex, trying to get closer to w3c URI spec.

Last char must be either: letter,number, ?,#, =, /

You need to login to post a comment.