简体   繁体   English

正则表达式模式匹配难度

[英]Regex Pattern Matching Difficulty

I'm having issues with understanding pattern matching. 我在理解模式匹配方面遇到了问题。 I've figured it out to a point but I'm having a lot of trouble with this specific pattern I need to match. 我已经把它弄清楚了,但我遇到了这个我需要匹配的特定模式的麻烦。

Requirements: Check for the format of the user name. 要求:检查用户名的格式。 It should start with a letter followed by letters, numbers, and periods. 它应该以字母开头,后跟字母,数字和句点。 A user name should be at least 6 characters long but no more than 12. 用户名长度应至少为6个字符,但不得超过12个。

This is what I have so far: 这是我到目前为止:

var user = document.getElementById('username').value;
var pos = user.search(/^[A-z](?=.*?[A-z])(?=.*?[0-9])\./);

Try this pattern 试试这种模式

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

Hope this helps! 希望这可以帮助!

Edit: 编辑:

Javascript to do the match 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")
}

It should start with a letter followed by letters, numbers, and periods. 它应该以字母开头,后跟字母,数字和句点。 A user name should be at least 6 characters long but no more than 12. 用户名长度应至少为6个字符,但不得超过12个。

So you want to allow a string that starts with a letter and has at least one dot or number and is between 5 and 12 characters. 因此,您希望允许以字母开头且至少包含一个点或数字且长度在5到12个字符之间的字符串。

In that case, use the following: 在这种情况下,请使用以下内容:

^[A-Za-z](?=.*\d.*)(?=.*[.].*)[A-Za-z\d.]{5,11}$
  • ^ match start. ^匹配开始。
  • [A-Za-z] a letter. [A-Za-z]一封信。
  • (?=.*\\d.*) positive lookahead - the following string contains at least 1 digit. (?=.*\\d.*)正向前瞻 - 以下字符串包含至少1位数。
  • (?=.*[.].*) positive lookahead - the following string contains at least 1 dot. (?=.*[.].*)正向前瞻 - 以下字符串包含至少1个点。
  • [A-Za-z\\d.]{5,11} the rest of the string contains between 5 and 11 letters, digits and dots (the total string between 6 and 12). [A-Za-z\\d.]{5,11}字符串的其余部分包含5到11个字母,数字和点(6到12之间的总字符串)。
  • $ match end. $ match end。

Note: - 注意: -

  • ?= the forward lookup does not affect the match position, so the match will continue at the second character. ?=正向查找不会影响匹配位置,因此匹配将在第二个字符处继续。
  • ?= an AND is implied between the forward lookups, so both need to be satisfied. ?=正向查找之间隐含AND,因此两者都需要满足。
^[a-zA-Z][a-zA-Z.]{5,11}$

这个应该适合你,因为你没有任何关于任何角色最小出现的约束。

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

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