繁体   English   中英

如何编写正则表达式匹配 word_char 但只有零或一个下划线

[英]How to write a regex matching word_char but only zero or one underscore

我有一个用户名要测试:

  1. 它至少由4个字符组成
  2. 它只能包含单词字符、数字和下划线(最多一次)
  3. 它应该以单词字符开头,不能以下划线结尾。

我写了这个正则表达式

^[a-zA-Z][^\W_]{2,}_?[a-zA-Z0-9]$

但我真的不知道如何限制下划线的出现(0-1 次)。

我怎样才能达到我的要求?

使用前瞻检查更具体的资格,然后应用\w{4,}的一般规则。

Regex101 演示

 const tests = ['_und', 'u_nd', 'un_d', 'und_', 'u_n_', 'u__d', '8_no']; for (i in tests) { document.write(tests[i] + ' => ' + /^(?=[az][^_]*_?[^_]+$)\w{4,}$/i.test(tests[i]) + "<br>"); }

(?=         #lookahead
  [a-z]     #a letter
  [^_]*     #zero or more non-underscores
  _?        #an optional underscore
  [^_]+$    #one or more non-underscores until the end of the string
)

它也可以在没有前瞻的情况下完成,但是 4 个或更多字符的长度检查变得隐式而不是显式。 换句话说,阅读该模式的人需要通过理解条件表达式并对实施的量词求和来确定字符串的最小长度为 4。

 const tests = [ 'und', '_und', 'u_nd', 'un_d', 'und_', 'u_n_', 'u__d', '8_no', 'u_derscore', 'un_erscore', 'und_rscore', 'unde_score', 'under_co_e', 'underscor_', '_nderscore' ]; for (i in tests) { document.write(tests[i] + ' => ' + /^[az](?:_[^\W_]{2,}|[^\W_]_[^\W_]+|[^\W_]{2,}_?[^\W_]+)$/i.test(tests[i]) + "<br>"); }

分解:

/                        #pattern delimiter
^                        #start of string anchor
[a-z]                    #alphabetical character
(?:                      #non-capturing group
  _[^\W_]{2,}            #underscore, two or more alnum characters (at least 3 characters)
  |                      #or
  [^\W_]_[^\W_]+         #alnum character, underscore, one or more non-underscore (at least 3 characters)
  |                      #or
  [^\W_]{2,}_?[^\W_]+    #two or more alnum characters, optional underscore, one or more alnum characters (at least 3 characters)
)                        #end of non-capturing group
$                        #end of string anchor
/                        #pattern delimiter
i                        #case-insensitive pattern modifier

暂无
暂无

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

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