URL正则表达式验证

13

我做了这个:

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

我已经使用验证器检查过了,但在我的页面上它没有起作用:

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;
}

我遇到了这个错误

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://*************************

你使用了哪个验证器?它是专门针对JS的吗?请记住,正则表达式在不同的环境中可能会有所不同。 - Michael Kopinsky
我使用了 JavaScript,但不知道出了什么问题。 - Y.G.J
6个回答

35

你需要转义特殊字符(在这种情况下是/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;
}

1
http://localhost:8000/memcache?message=Cache+flushed%2C+all+keys+dropped. 这个有什么问题? - nguyên
由于该函数仅适用于没有端口的域名和IP地址。 - Delowar Hossain

2

即使问题已被接受,我仍然会发布。

那个正则表达式仍然不完整。

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

这是我使用的:

~^
(?: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

涵盖http(s)、ftp(s)和.co.uk TLD等内容。还包括子域名,可以是1个字符(用于网页的移动版本m.example.com),但不允许m-.example.com
当然,有些人可能会对正则表达式的完整性提出异议,因为.pro TLD要求至少有4个字符作为域名. ;-)
此外,IDN域名只有在转换后(即以“xn--”格式)才能通过我的正则表达式。

我该如何使用它? - user3808307

1

如果您想知道URL是否真的存在:

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);
}

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

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

3
这里可能需要一些解释。 - user3483203

0
经过长时间的研究,我构建了这个正则表达式。我希望它也能帮助其他人……
   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')
 }

0

正如Nick所说,你必须转义\.,除非你使用另一个分隔符,这样你的正则表达式将变成:

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

但请注意,您的正则表达式将匹配类似于以下的URL:

http://....aa.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接