validate url without www. or http://

强颜欢笑 提交于 2019-12-13 00:33:31

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4691070/validate-url-without-www-or-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!