2010-11-30 78 views
7

我做了:URL正則表達式驗證

/^(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://************************* 
+0

你使用了什麼驗證器?它是JS特定的?請記住,正則表達式因環境而異。 – 2010-11-30 14:36:20

+0

我已經使用js one ...我不知道什麼是錯 – 2010-11-30 14:43:30

回答

18

您必須轉義您的特殊字符(/.www在此情況)和ATT失蹤後/,像這樣:

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

我是怎麼錯過的! :-) – 2010-11-30 14:41:17

0

正如尼克說你有,除非你使用其他delimitor逃脫\.讓你的正則表達式將變爲:

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

但要知道,你的正則表達式匹配的網址,如:

http://....aa. 
1

我會後,雖然問題已被接受。

該正則表達式仍然不完整。

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頂級域名等。還包括可以是1個字符長度的子域(移動版本的網頁爲m.example.com),但不允許m-.example.com

當然,有些人可能會反對正則表達式的完整性,因爲.pro TLD需要至少4個字符作爲域名。 ;-)

此外,IDN域名只會在轉換後通過我的正則表達式(即「xn--」格式)。

0

以防萬一你想知道的網址確實存在:

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

經過長期的研究後,我建立這個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') 
}