【问题标题】:Regex for URL Validation用于 URL 验证的正则表达式
【发布时间】:2011-06-17 23:51:31
【问题描述】:

我有一个可能是 URL 的字符串。我想通过正则表达式确定它是否是 Http/FTP URL。如果字符串是有效的 URL,那么我会将其设为超链接和蓝色等,如果它不是基于正则表达式 exp 的 ture 或 false 的 URL,我想进一步决定..

什么是最好的正则表达式?

【问题讨论】:

标签: regex


【解决方案1】:
 isUrlValid(str)
{
   var pattern = new RegExp('^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$', 'g'); 
   return pattern.test(str);
}

它通过了所有这些测试用例:

【讨论】:

    【解决方案2】:

    以防万一您想知道该 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);
    }
    

    【讨论】:

    • 该功能需要多长时间?
    【解决方案3】:

    这个 perl 代码非常准确,可能并不完美。第 1 组包含 httpftp

    if ($str =~ /^(http|ftp):\/\/[\w.%@]+(:?[?].*)?/) {
        print "matches $1\n";
    } else {
        print "no match\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2015-11-08
      • 2018-08-06
      • 2011-05-16
      • 2012-01-24
      • 1970-01-01
      相关资源
      最近更新 更多