1

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/

2 Answers 2

1

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*)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.