无法以字符开头或结尾的用户名
我试图用正则表达式来实现这些规则:
- 可以包含小写和大写字母和数字
- 可以包含下划线和句点
- 连续不能包含2个下划线
- 不能连续包含2个句点
- 不能以下划线或句号开头或结尾
- 不能包含带重音的字母
- 长度必须在3到28个字母之间
有效:
Spicy_Pizza 97Indigos Infinity.Beyond
无效:
_yahoo powerup. un__real no..way
这是我目前的正则表达式:
^(?:[a-zA-Z0-9]|([._])(?!\1)){3,28}$
除了以下划线或句号开头和结尾的例外之外,所有规则似乎都有效。
听起来你只需要在字符串的第一个和最后一个字符处添加一个字母数字检查。 因为这会占用2个字符,所以将内部重复从{3,28}
更改为{1,26}
:
^[A-Za-z\d](?:[a-zA-Z0-9]|([._])(?!\1)){1,26}[A-Za-z\d]$ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^
我更喜欢明确表示字符串不能以句点或下划线开头或结尾,而不是规定在字符串的开头和结尾允许哪些字符。
r = / \A # match beginning of string (?![._]) # next char cannot be a period or underscore (?: # begin non-capture group [a-zA-Z0-9] # match one of chars in indicated | # or ([._]) # match a period or underscore in capture group 1 (?!\1) # next char cannot be the contents of capture group 1 ){3,28} # end non-capture group and execute non-capture group 3-28 times (?