0

I am pretty new to regex expression I need to validate website url with Regex expression through java script for -- example www.google.com

Http is optional in my case

Please help me out thank you very much

robert
  • 1
  • 1
    Possible duplicate of about 100+ other post. You can take almost any url regex that you find suitable for your needs and wrap the scheme with parentheses followed by a question mark. ex. `(https?://)?` – Joe Apr 08 '11 at 20:51
  • possible duplicate of [Regex to match URL](http://stackoverflow.com/questions/1141848/regex-to-match-url) – Evert Apr 08 '11 at 21:29

2 Answers2

0

(http|https)://([\w-]+.)+[\w-]+(/[\w- ./?%&=]*)?

from: http://www.webpronews.com/validating-a-url-with-regular-expressions-2006-10

Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77
0

Here is a regex for you that takes into consideration if the URL contains username, if it is an IP, validates general TLDs, and some more.

^((http|https|ftp)\://)?([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$ 

Here is how it works: regex analyzer

This has been taken from regexlib.com, and only changed so that the scheme (http, https, etc) part is optional and replaced & with &.

Simpler version

Here is a simpler version, which works well most of the time:

^((ftp|http|https):\/\/)?(\w+:{0,1}\w*@)?((\S+.[a-z]{2,6})|([0-9\.]+))(:[0-9]+)?(\S+)?$

Here is how it works: regex analyzer

In case you´re interested:

Group 2: The scheme (eg. http)
Group 3: Username and password (optional)
Group 4: Either hostname or IP
Group 5: If group 4 is hostname, this group is the hostname (eg. stackoverflow.com)
Group 6: If group 4 is an IP, this is the IP address
Group 7: Is the port (optional)
Group 8: Is the path and query, actually the rest (eg. /hello?world=foo)

Try it out on regexpal.

mqchen
  • 4,195
  • 1
  • 22
  • 21