首页 > 解决方案 > 用户名的正则表达式

问题描述

我正在尝试为符合以下条件的用户名编写正则表达式...

必须介于 6 到 16 个字符之间,其中任意 4 个必须是字母(尽管不一定是连续的),还可以包含字母、数字、破折号和下划线。

所以_1Bobby1_and-Bo-By19-会匹配,但不会_-bo-_匹配-123-456_

我试过了:

^(?=.*[a-zA-Z].{4})([a-zA-Z0-9_-]{6,16})$

但这似乎不起作用,我在网上查看并找不到任何有效的方法,并使用 Regexper 可视化表达式并尝试从头开始构建它。

任何指针将不胜感激。

标签: asp.netregex

解决方案


正则表达式可用于验证用户名

^(?=.{6,16}$)(?=(?:.*[A-Za-z]){4})[\w-]+$

正则表达式分解

^ #Start of string
(?=.{6,16}$) #There should be between 6 to 16 characters
  (?=
    (?:.*[A-Za-z]){4} # Lookahead to match 4 letter anywhere in string
  )
[\w-]+ #If above conditions are correct, match the string. It should only contain dgits, alphabets and dash
$ #End of string. Not necessary as the first check (?=.{6,16}$) itself does that

推荐阅读