Javascript URL 正则表达式验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4314741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:51:54  来源:igfitidea点击:

URL regex validation

javascriptregex

提问by Y.G.J

i made that:

我做到了:

 /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}

and checked it with a validator but on my page it is not working:

并使用验证器检查它,但在我的页面上它不起作用:

var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) { 
    alert("url error");
    return false;
}

i get this error

我收到这个错误

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC


Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************

回答by Nick Craver

You have to escape your special characters (/and that .after wwwin this case) and att the missing trailing /, like this:

您必须转义您的特殊字符(在这种情况下/.在后面www)并添加缺少的尾随/,如下所示:

var re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
if (!re.test(url)) { 
    alert("url error");
    return false;
}

回答by Linus Kleen

I will post, although the question has been accepted.

我会发布,尽管问题已被接受。

That regex is still incomplete.

该正则表达式仍然不完整。

http://www.-1-.deis not a valid domain name but would pass your test.

http://www.-1-.de不是有效的域名,但会通过您的测试。

Here's what I use:

这是我使用的:

~^
(?:ht|f)tps?://

(?:[a-z0-9] (?:[a-z0-9-]*[a-z0-9])?      \.)*

(?:[a-z0-9][a-z0-9-]{0,62}[a-z0-9])
(?:\.[a-z]{2,5}){1,2}

$~ix

Covers http(s), ftp(s) and .co.uk TLDs and the like. Also covers subdomains which can be 1 character in length (m.example.comfor mobile versions of webpages) but will not allow m-.example.com.

涵盖 http(s)、ftp(s) 和 .co.uk TLD 等。还涵盖长度可以为 1 个字符的子域(m.example.com对于网页的移动版本),但不允许m-.example.com.

Surely some might object as to the regex's completeness, since .proTLDs require at least 4 characters as a domain name. ;-)

当然有些人可能会反对正则表达式的完整性,因为.proTLD 需要至少 4 个字符作为域名。;-)

Also IDN domain names will only pass my regex after conversion (i.e. in the "xn--" format).

此外,IDN 域名只会在转换后通过我的正则表达式(即“xn--”格式)。

回答by Roger

Just in case you want to know if the url really exists:

以防万一您想知道该网址是否真的存在:

function url_exist($url){//se passar a URL existe
    $c=curl_init();
    curl_setopt($c,CURLOPT_URL,$url);
    curl_setopt($c,CURLOPT_HEADER,1);//get the header
    curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
    if(!curl_exec($c)){
        //echo $url.' inexists';
        return false;
    }else{
        //echo $url.' exists';
        return true;
    }
    //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);
    //return ($httpcode<400);
}

回答by Aamir

After a long research I build this reg expression. I hope it will help others too.......

经过长时间的研究,我构建了这个 reg 表达式。我希望它也能帮助其他人......

   url = 'https://google.co.in';
   var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\|\\^\[\]`]+)?$/;
  if (!re.test(url)) { 
     alert("url error");
   return false;
 }else{
 alert('success')
 }

回答by Vin S

var regForUrl = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

if (!regForUrl.test(url)) {
    alert('Invalid URL-- missing "http://" or "https://"');
}

回答by Toto

As said Nick you have to escape \and .unless you're using another delimitor so your regex will become :

正如尼克所说,您必须逃脱\.除非您使用另一个分隔符,否则您的正则表达式将变为:

var re = '~(https?)://)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}\.?~';

But be aware that your regex will match url like:

但请注意,您的正则表达式将匹配以下网址:

http://....aa.