简体   繁体   English

AngularJS ng模式网站模式

[英]AngularJS ng-pattern website pattern

/^[_a-z0-9]+(\.[_a-z0-9]+)*[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,7})$/

That's the pattern. 这就是模式。 It says "ok" when it's correct, and "not ok" when it's incorrect. 正确时显示“ ok”,不正确时显示“ not ok”。 So it says "ok" on www.google.com, but "not ok" when I type http://www.google.com 因此,它在www.google.com上显示“确定”,但在我输入http://www.google.com时显示“不确定”

What I'd like is this pattern to allow http:// too, but it should never be a requirement. 我想要的是也允许http://的这种模式,但这绝不是必需的。

You can use the following regular expression, which I lifted off borrowed from the documentation of the Perl module URI on CPAN (escaping of slashes mine). 您可以使用下面的正则表达式,我 升空 来自的文档借用上CPAN的Perl模块URI (逃避斜线矿)。

/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/

It will give you all the different parts of the URI in capture groups. 它将为您提供捕获组中URI的所有不同部分。

Those parts are: 这些部分是:

  • scheme ( http: ) 方案( http:)
  • authority (not applicable here) 权限(此处不适用)
  • path ( www.google.com ) 路径( www.google.com
  • query ( q=querystring ) 查询( q = querystring
  • fragment ( #anker ) 片段( #anker

See https://regex101.com/r/vS5qO1/1 to try it out. 请参阅https://regex101.com/r/vS5qO1/1进行尝试。

Also note that this will parse all types of URIs, not only http(s). 另请注意,这将解析所有类型的URI,而不仅是http(s)。 So stuff like ftp://anonymous@example.org will also work. 因此,诸如ftp://anonymous@example.org之类的东西也将起作用。

If you're looking to only allow http/https URL schemes (when the scheme is provided), the following modification to your regular expression will do the trick: 如果您允许使用http / https URL方案(提供方案时),则对正则表达式进行以下修改将达到目的:

/^(http:\\/\\/|https:\\/\\/)?[_a-z0-9]+(\\.[_a-z0-9]+)*[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[az]{2,7})$/

You can use my answer as an example of how to add the url scheme group to your existing regex, but credit @simbabque, as he has a much more complete answer. 您可以以我的答案为例,说明如何将url方案组添加到现有的正则表达式中,但是要感谢@simbabque,因为他的答案更为完整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM