[英]Regex Pattern Matching Difficulty
我在理解模式匹配方面遇到了问题。 我已经把它弄清楚了,但我遇到了这个我需要匹配的特定模式的麻烦。
要求:检查用户名的格式。 它应该以字母开头,后跟字母,数字和句点。 用户名长度应至少为6个字符,但不得超过12个。
这是我到目前为止:
var user = document.getElementById('username').value;
var pos = user.search(/^[A-z](?=.*?[A-z])(?=.*?[0-9])\./);
试试这种模式
var pattern = /^[A-Za-z][A-Za-z.0-9]{5,11}$/
^ matches beginning of file.
[A-Za-z] = matches first letter
[A-Za-z.0-9] = Matches a-z both A-Z and a-z the . (dot) character and numbers 0-9
{5,11} = tells that the last character "group" should have between 5 or 11 occurrences. witch makes the total string between 6 and 12 characters long.
$ = matches end of string
希望这可以帮助!
编辑:
Javascript来做匹配
var pattern = /^[A-Za-z][A-Za-z.0-9]{5,11}$/
//assuming the var username contains the username
if(username.match(pattern)){
alert("Valid pattern");
}
else{
alert("Invalid pattern")
}
它应该以字母开头,后跟字母,数字和句点。 用户名长度应至少为6个字符,但不得超过12个。
因此,您希望允许以字母开头且至少包含一个点或数字且长度在5到12个字符之间的字符串。
在这种情况下,请使用以下内容:
^[A-Za-z](?=.*\d.*)(?=.*[.].*)[A-Za-z\d.]{5,11}$
^
匹配开始。 [A-Za-z]
一封信。 (?=.*\\d.*)
正向前瞻 - 以下字符串包含至少1位数。 (?=.*[.].*)
正向前瞻 - 以下字符串包含至少1个点。 [A-Za-z\\d.]{5,11}
字符串的其余部分包含5到11个字母,数字和点(6到12之间的总字符串)。 $
match end。 注意: -
?=
正向查找不会影响匹配位置,因此匹配将在第二个字符处继续。 ?=
正向查找之间隐含AND,因此两者都需要满足。 ^[a-zA-Z][a-zA-Z.]{5,11}$
这个应该适合你,因为你没有任何关于任何角色最小出现的约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.