1

我需要使用正则表达式验证 url。应接受的有效格式如下:

users.kathir.com
www.kathir.com

我目前正在使用以下正则表达式:

^[a-z0-9-]+(\.[a-z0-9-])+(.[a-z])

但它接受 www.google 作为有效的,但它应该只接受 google.com 或 www.google.com。请建议

4

2 回答 2

2

我用这个,效果很好:

function checkUrl(url){
    return url.match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/);
}

希望有帮助:)

于 2012-05-11T11:49:32.030 回答
0

The answer provided by user will also validate those regex in which there is no .com|edu|org etc at the end to make it more appropriate I have modify the regex which works fine for me and also want to share with you

var pattern = /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])+(.[a-z])?/;
var regex = new RegExp(pattern);
var website_url = $("#website_url").val();// url of the website
if (website_url.match(regex)) {
    return true
} else {
    return false;
}

if you like it do an Upvote

于 2014-12-19T05:40:15.437 回答