简体   繁体   English

使用正则表达式验证用户名

[英]Validating userName using Regex

  1. The only numbers in the username have to be at the end.用户名中唯一的数字必须在末尾。 There can be zero or more of them at the end.最后可以有零个或多个。

  2. Username letters can be lowercase and uppercase.用户名字母可以是小写和大写。

  3. Usernames have to be at least two characters long.用户名必须至少有两个字符长。 A two-letter username can only use alphabet letter characters.两个字母的用户名只能使用字母字符。

I'm trying with this but I'm stalled.我正在尝试这个,但我停滞不前。 /\\d+$\\w+/gi

/^[az]{2,}\\d*$/i is: /^[az]{2,}\\d*$/i是:

^     : the begining
[a-z] : a character (a to z), you can add as many allowed characters as you want
{2,}  : at least 2 of them
\d*   : 0 or more digits 
$     : the end
i     : ignore case sensetivity (both lowercases and uppercases are allowed)

Username having characters and digit and min 2 character long用户名包含字符和数字,最少 2 个字符长

/^[a-zA-Z]{2,}\d*$/i

Test result :测试结果 :

UserNam9 = pass
9username = fail
Userna99 = pass
usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = pass
Us = pass
U = fail
/^[A-z]{2,}[A-z0-9]{0,}$/
/^ // start of line
[A-z]{2,} //alphabet characters 2 or more
[A-z0-9]{0,} //numbers and alphabet 
$/ // end of line

You've missed cases when there's a letter in the start, followed by 2 or more numbers.如果开头有一个字母,后面跟有 2 个或更多数字,您就会漏掉这种情况。

U99 = fail
d345 = fail

My solution passes these tests, as well:我的解决方案也通过了这些测试:

/^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i

Using positive lookahead I am making sure that in the second case there are at least 3 alphanumeric characters.使用正向前瞻,我确保在第二种情况下至少有 3 个字母数字字符。

Simplified version of /^[az]{2,}\\d*$|(?=\\w{3,})^[az]{1,}\\d+$/i : /^[az]{2,}\\d*$|(?=\\w{3,})^[az]{1,}\\d+$/i简化版本:

/^\D(\d{2,}|\D+)\d*$/i

Code explanation:代码说明:

  1. ^ - start of input ^ - 输入开始
  2. \\D - first character is a letter \\D - 第一个字符是一个字母
  3. \\d{2,} - ends with two or more numbers \\d{2,} - 以两个或多个数字结尾
  4. | - or - 或者
  5. \\D+ - has one or more letters next \\D+ - 接下来有一个或多个字母
  6. \\d* - and ends with zero or more numbers \\d* - 并以零个或多个数字结尾
  7. $ - end of input $ - 输入结束
  8. i - ignore case of input i - 忽略输入的大小写

This is my answer, it passed all the tests:这是我的答案,它通过了所有测试:

/^[a-z][a-z]+\d*$|^[a-z]\d{2,}$/i
  • First Part: 2 letters (or more) and zero or more numbers第一部分:2 个字母(或更多)和零个或多个数字
  • Or或者
  • Second Part: 1 letter and 2 or more numbers第二部分:1 个字母和 2 个或更多数字

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

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