danyo
danyo

Reputation: 5856

modifying regex to detect urls

I have the following regex, which detects a url based on it having http:// when entered:

(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)

So with the above if i enter http://www.google.com this works great. However, if i was to miss the http:// out and even the www. it wont detect the above as a url.

Is there an easy way to adapt the above to accept urls without http:// or www. even though i dont really know how regex works fully? I ahve been playing with the following site:

http://regexpal.com/

Upvotes: 1

Views: 62

Answers (2)

PhilTrep
PhilTrep

Reputation: 1641

For a more complete regex match:

/^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/xiS

Upvotes: 0

pierroz
pierroz

Reputation: 7880

You can make http:// and www. optional. It can be achieved with the question mark '?' which means 0 or 1 occurrence of the pattern.

((http|https|ftp|ftps)\:\/\/)?(www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)

Upvotes: 1

Related Questions