为什么正则表达式不能正确验证网站URL

Why does the regular expression not validate the website URL properly?

本文关键字:验证 网站 URL 正则表达式 不能 为什么      更新时间:2023-10-17

以下是我用于验证网站URL的URL表达式(regex):

/(https?:'/'/)(www)?[A-Za-z0-9.'-@_~]+'.[A-Za-z]{2,}(:[0-9]{2,5})?('/[A-Za-z0-9'/_'-.~?&=]*)*/

我的angular JS代码实现如下:

 <md-input-container class="md-block" style="margin-top:20px;">
        <label>Website</label> 
        <input ng-model="schoolDetails.website" name="website" ng-change="editField()" type="url" ng-pattern="/(https?:'/'/)(www)?[A-Za-z0-9.'-@_~]+'.[A-Za-z]{2,}(:[0-9]{2,5})?('/[A-Za-z0-9'/_'-.~?&=]*)*/">
        <div ng-messages="schoolDetailsForm.website.$error">
           <div ng-message="pattern">Please enter a valid website</div>
       </div> 
</md-input-container>

假设我给出有效的URL http://www.bharatividyapeeth.edu,它工作得很好。如果我给出无效的URL,http://www.会显示错误消息,但当我输入无效的URL时,http://www.bharatividyapeeth不会显示错误消息并将其作为有效的URL接受。

有人能纠正我的代码以正确验证网站URL吗?

谢谢。

您的任务似乎需要一个更简单的regex。所以我只修改你的正则表达式。虽然这将适用于大多数URLs,但在某些地方也会失败

/https?:'/'/(www'.)?(?!www'.)([A-Za-z0-9'-@_~]+'.)[A-Za-z]{2,}(:[0-9]{2,5})?('.[A-Za-z0-9'/_'-~?&=]+)*/

这对我来说似乎是正确的:

var str = 'http://www.bharatividyapeeth.in'
var reg = /(http|https)(:'/'/)+?(w{3}('.'w*'.))+(edu|com|co'.in|in)/gi;
document.querySelector('pre').innerHTML = str.match(reg)[0];
<pre></pre>

请测试并查看此正则表达式是否适用于您:

(https?:'/'/(?:www'.|(?!www))[^'s'.]+'.[^'s]{2,}|www'.[^'s]+'.[^'s]{2,})

这个将匹配以下内容:

http://www.bharatividyapeeth.edu
https://www.bharatividyapeeth.edu
www.bharatividyapeeth.edu

不匹配:

http://www.bharatividyapeeth
https://www.bharatividyapeeth
www.bharatividyapeeth

你可以在这里测试:

http://regexr.com/