Regex for hyperlinking URLs & e-mail addresses

tuthlis
tuthlis used Ask the Experts™
on
I've got bits and pieces of text flowing through a program into a database for display on the web only.  Some of these bits and pieces may contain web site URLs (almost never beginning with http://, but www instead) and e-mail addresses.  I'd like to be able to identify and wrap up those pieces in <a> tags (i.e. <a href="[URL]"> and <a href="mailto:[EMail]">), much like this question is hyperlinked in certain places.

I could hobble my way through regular expressions (I'm a .NET regex newbie) but I was curious if the experts out there had a couple of regular expressions along with code they already use for this purpose?  I found this one while searching around:
(?<url>http://(?:[\w-]+\.)+[\w-]+(?:/[\w-./?%&=]*)?)
 but I don't completely understand what it does and I want to know if there's one that's tried and tested and true for both web site URLs and e-mail addresses.  Or if someone out there has a better method not using Regular Expressions, I'd love to know what is also.  

Thanks for your time.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Here's what I use:
To find an email address:

^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$

or for RFC compliance:

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

To find a URL:
(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

Directly from www.regexlib.com!

The easiest is to search the above site for "url" and see if they have what you need.

In terms of code, all I can offer is that you should use the System.Text.StringBuilder in stead of just strings for search & replace. You'll search for a substring matching the URL regular expression and replace with the same text wrapped in <A ...></A> etc.

I hope that helps!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial