Link A URL With Regex

I recently had a need to find a url within a large amount of text and turn it into a hyper link. Knowing that I am just a regex noob I opted to find someone else that could just give me some regex 🙂  I started with but everything there was exceptionally simple. Simple usually works but the client I’m working with always finds clever ways to do something unexpected. So I needed something that would detect any URL that is possible under the sun.

After a few minutes I found Ivan Porto Carrero’s website which had the following regex:

(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?

It’s a pretty stinkin’ big regex but it sure does the job. I tried it with any url I could think of as well as the ones listed on Ivan’s site.
So there you have it. A big change from the pinball stuff but I needed to store this one where I could find it easily. I’m sure I’ll need it again in the future!

Author: Jeremy

See all posts by (34)

Leave a Reply