Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic web-address validation regex?

I am looking for a regex that validates simple website addresses, i.e.

  • http://www.stackoverflow.com
  • www.stackoverflow.com
  • stackoverflow.com
  • stack-overflow.co.it

I need it for contact details, 'Website' field, then when user click it opens IE, it doesn't have to be strict, I just don't want the user to enter 'I love milk' or 'google' etc.

I thought instead shrinking my mind writing my own struggling to find exception, why won't I learn from the community experience, anyone who has a good regex or a link please post.

Thanks a lot.

like image 992
Shimmy Weitzhandler Avatar asked Feb 27 '23 18:02

Shimmy Weitzhandler


2 Answers

From RFC 3986, Uniform Resource Identifiers (URI): Generic Syntax, appendix B (p. 50):

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

If the URI matches this regular expression, it's well formed. The match groups give you the various pieces, which are:

scheme    = $2
authority = $4
path      = $5
query     = $7
fragment  = $9
like image 88
Wayne Conrad Avatar answered Mar 10 '23 20:03

Wayne Conrad


https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?

excerpt from http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/


 (https?://)?([-\w\.]+)+(:\d+)?

revise per suggestion, but i think people should better follow the clue and figure out the answer themselves. anyway, even copy/paste, people should know what they are doing.

like image 25
Dyno Fu Avatar answered Mar 10 '23 22:03

Dyno Fu