用于网站或网址验证的正则表达式 [英] Regex for website or url validation

查看:95
本文介绍了用于网站或网址验证的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个很常见的问题&有这么多答案,但我的问题不同,我想接受以下所有格式的网址:

I know this is so common question & there are so many answers for this, but my problem is different, I want to accept the URL with all below formats:

http://www.sample.com
https://www.sample.com
http://www.sample.com/xyz
www.sample.com
www.sample.com/xyz/#/xyz
sample.com

// & much more ...

所以这里的想法是,我允许用户进入那里的网站&另一个用户只需点击已保存的网站&去用户网站。因此,限制用户输入正确的URL并不是一个好主意,他们可以输入上述任何格式。这是我正在使用的正则表达式,但它只检查URL是否从正确的协议开始:

So here idea is, I am allowing the user to enter there website & another user can just click on the saved website & go to users website. So here it's not a good idea to restrict the user to input proper URL, they can enter any of the above formats. Here is the regex I am using right now, but that only checks if URL starts from proper protocol:

^(ftp|http|https):\/\/[^ "]+$


推荐答案

使用正则表达式 ^((https?| ftp | smtp):\ / \ /)?(www。)?[a-z0-9] + \。[ az] +(\ / [a-zA-Z0-9#] + \ /?)* $

这是一个我刚刚建立的基本版本。谷歌搜索可以给你更多。

This is a basic one I build just now. A google search can give you more.

这里


  • ^应该以

  • 开头((https?| ftp | smtp)://)?可能包含或不包含任何这些协议

  • (www.。)?可能有也可能没有www。

  • [a-z0-9] +(。[az] +)url和域以及子域(如果有的话)最多2个级别

  • (/ [a-zA-Z0-9#] + /?)* /?可以包含文件的路径,但不是必需的。最后可能包含 /

  • $应该在那里结束

  • ^ Should start with
  • ((https?|ftp|smtp)://)? may or maynot contain any of these protocols
  • (www.)? may or may not have www.
  • [a-z0-9]+(.[a-z]+) url and domain and also subdomain if any upto 2 levels
  • (/[a-zA-Z0-9#]+/?)*/? can contain path to files but not necessary. last may contain a /
  • $ should end there

var a=["http://www.sample.com","https://www.sample.com/","https://www.sample.com#","http://www.sample.com/xyz","http://www.sample.com/#xyz","www.sample.com","www.sample.com/xyz/#/xyz","sample.com","sample.com?name=foo","http://www.sample.com#xyz","http://www.sample.c"];
var re=/^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/;
a.map(x=>console.log(x+" => "+re.test(x)));

这篇关于用于网站或网址验证的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆