validate url without www. or http://

2019-07-27 10:09发布

I'm looking to validate an URL. I have already a script that validates to not allow www. and http:// but i need to also validate for .co.uk .com etc.

My script won't run if they enter something like example.co.ukff.

I have this for a full URL:

^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i

I just need to validate the end .co.uk or .com etc.

2条回答
做自己的国王
2楼-- · 2019-07-27 10:30

Far from pretending this to be the ideal regex to match urls, the particular problem of only matching urls which do not begin with www can be resolved with a negative lookahead : (?!www\.) meaning that the following text should not be www.

Therefore, your regex adapted with this negative lookahead:

^(?!www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$

matches the following urls

google.com
google.com/
goggle.com/q
google.com/q?q=1&h=en
google.co.uk
google.co.uk/
goggle.co.uk/q
google.co.uk/q?q=1&h=en
w.google.com
w.google.com/
w.goggle.com/q
w.google.com/q?q=1&h=en
209.85.149.105
209.85.149.105/
209.85.149.105/q
209.85.149.105/q?q=1&h=en
209.85.149.105:80
209.85.149.105:80/
209.85.149.105:80/q
209.85.149.105:80/q?q=1&h=en
example.domain.bogus.number.of.subdomains/index.htm

but not those:

www.google.com
www.google.com/
www.google.co.uk
www.google.co.uk/
www.google.co.uk/q
www.google.co.uk/q?q=1&h=en
http://209.85.149.105/
http://209.85.149.105:80/
http://www.google.com
https://www.google.com
http://google.com
https://google.com
查看更多
劳资没心,怎么记你
3楼-- · 2019-07-27 10:31

Try This...

/^http:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/

It's working exactly what you want.

it takes with or with out http://, https://, and www.

查看更多
登录 后发表回答