moh*_*sti 44 html php java regex perl
我正在尝试创建一个正则表达式来根据这些条件验证用户名:
_username
/ username_
/ .username
/ username.
).user_.name
).user__name
/ user..name
).这就是我到目前为止所做的事情; 听起来它强制执行所有标准规则但是第5条规则.我不知道如何添加第五条规则:
^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$
Run Code Online (Sandbox Code Playgroud)
Ωme*_*ega 185
^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
?????????????????????????????????????????????? ?????????
? ? ? ? no _ or . at the end
? ? ? ?
? ? ? allowed characters
? ? ?
? ? no __ or _. or ._ or .. inside
? ?
? no _ or . at the beginning
?
username is 8-20 characters long
Run Code Online (Sandbox Code Playgroud)
Jam*_*urz 12
尽管我喜欢正则表达式,但我认为可读性是有限的
所以我建议
new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");
Run Code Online (Sandbox Code Playgroud)
它更长,但不需要维护者打开 expresso 来理解。
当然你可以评论一个很长的正则表达式,但是读过它的人必须依赖于信任......
对Phillip的回答略有修改,修复了最新的要求
^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
Run Code Online (Sandbox Code Playgroud)
我想你必须在这里使用Lookahead表达式.http://www.regular-expressions.info/lookaround.html
尝试
^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
[a-zA-Z0-9]
一个字母数字那么(
_(?!\.)
a _后面没跟a.要么
\.(?!_)
一个 .没有跟着_ OR
[a-zA-Z0-9]
一个字母数字)FOR
{6,18}
至少6到最多18倍然后
[a-zA-Z0-9]
一个字母数字
(第一个字符是alphanum,然后是6到18个字符,最后一个字符是alphanum,6 + 2 = 8,18 + 2 = 20)