需要正则表达式来验证用户名。

5
需要一个正则表达式来验证用户名,该用户名必须满足以下条件:
  1. 允许尾随空格,但不能在字符之间加空格
  2. 必须至少包含一个字母,可以包含字母和数字
  3. 最多7-15个字符(字母数字组合)
  4. 不能包含特殊字符
  5. 下划线是允许的
我不确定如何做到这一点。任何帮助都将不胜感激。谢谢。
这是我正在使用的,但它允许字符之间有空格。
"(?=.*[a-zA-Z])[a-zA-Z0-9_]{1}[_a-zA-Z0-9\\s]{6,14}"

示例:用户名 用户名中不允许有空格


为什么必须使用单个正则表达式?通常,几行清晰的代码比一个扭曲的正则表达式更好。允许尾随空格似乎很奇怪;它们实际上是用户名的一部分吗,还是被忽略了?您真的想将“fred”和“fred ”视为不同吗?尾随空格是否计入7-15的最大长度?用户名必须至少为7个字符吗,还是存在可变的最大长度,可以从7到15的任何位置(基于什么)?什么是“特殊字符”? “123_456”有效吗(即,下划线是否计为规则2的字母)? - Keith Thompson
1个回答

4

试试这个:

foundMatch = Regex.IsMatch(subjectString, @"^(?=.*[a-z])\w{7,15}\s*$", RegexOptions.IgnoreCase);

这也允许使用_,因为您在尝试中允许了这个。

所以基本上我使用三条规则。一条是检查至少存在一个字母。 另一条是检查字符串是否仅由字母加上_组成,最后接受尾随空格和至少7个最多15个字母。你走在了正确的轨道上。继续努力,你也会在这里回答问题:)

分解:

    "
^           # Assert position at the beginning of the string
(?=         # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .        # Match any single character that is not a line break character
      *     # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [a-z]    # Match a single character in the range between “a” and “z”
)
\w          # Match a single character that is a “word character” (letters, digits, etc.)
   {7,15}   # Between 7 and 15 times, as many times as possible, giving back as needed (greedy)
\s          # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *        # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$           # Assert position at the end of the string (or before the line break at the end of the string, if any)
"

@user1078081 你好吗?你能解释一下这是如何可能的吗? - FailedDev
这显示了一个无效的转义序列(有效的是\b \t \n \f \r " ' \),语法错误模式。我该怎么修复它? - 1078081
1
你使用的是哪种编程语言? - FailedDev
@NotEmpty @Pattern(regexp = "^(?=.[a-z])\w{7,15}\s$") private String username; - 1078081
这是针对Hibernate的吗?你可能需要像在原始正则表达式中一样使用双反斜杠。 - Alan Moore
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接