0

I want to have a regex that will validate url in following way

http://www.google.com   ->valid url
www.google.com          ->valid url
google.com              ->in-valid url
http://google.com       ->in-valid url

I have tried following regex from here

/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/

but it doens't validate the existence of www

6
  • What regex flavor/language are you using? Commented Mar 14, 2016 at 20:00
  • I am using regexp/php as validating with preg_match Commented Mar 14, 2016 at 20:02
  • Wait, what? You want to enforce that the domain starts with www., but you include bits in your regex that allow for IPv4 addresses in the form http://0.0.0.0/? Did you just dump someone else's regex in your question in an attempt to make it look like you make some effort? Commented Mar 14, 2016 at 20:09
  • @hvd I didn't say I have made that. Did I say that? I said I have tried. Seriously negative vote? Commented Mar 14, 2016 at 20:10
  • You certainly implied it. If it's someone else's regex, include a mention of the author in your question. See How to reference material written by others. Commented Mar 14, 2016 at 20:12

3 Answers 3

1

You can use this regex in PHP:

$re = '~\b(?:https?://)?(www\.[^.\s]+\.[^/\s]+|\d+\.\d+\.\d+\.\d+)~';

RegEx Demo

This regex will enforce www. after optional htpp:// or https:// before it.

Another option in PHP is to use parse_url function and check for result['host'] array entry.

Sign up to request clarification or add additional context in comments.

Comments

0

Put www in your regex:

/^(?:https?:\/\/)?(www(\.[\w-]+)+|\d+(\.\d+){3})/

I also improved it a bit (so it doesn't match "www......" etc)

See live demo.

2 Comments

Shouldn't IP address be matched only till 255.255.255.255 ?
@noob sure, but that's not what op is asking about. Fixing the ip range would overly complicate the answer.
0

To match www you will have to use regex like this.

Regex: (?:https?:\/\/)?www\.[a-zA-Z0-9.-]+.[a-zA-Z]+|(?:\d\.?){4}

Regex101 Demo

3 Comments

How about URLs with "_"?
Are you sure about the .? Should be \., shouldn't it?
Try this as input: www.test9/com That should demonstrate the mistake I mean.

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.