Akshay
Akshay

Reputation: 1

Regex for URL Validation

I have a string which may be an URL. I want to determine if its a Http/FTP URL by a regex. If the string is valid URL then I will make it hyperlink and a blue color etc, if its not an URL based on ture or false of regex exp i want to decide further..

Whats is best Regex for it ?

Upvotes: 0

Views: 829

Answers (3)

ajaykumar1301
ajaykumar1301

Reputation: 36

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

It passes all this test cases:

Upvotes: 1

Roger
Roger

Reputation: 8576

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

Upvotes: 0

kelloti
kelloti

Reputation: 8951

This perl code is pretty accurate, probably not perfect. Group 1 contains either http or ftp

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

Upvotes: 0

Related Questions