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

时间:2011-12-02 19:27:58

标签: regex

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

  1. 应该允许尾随空格但不允许字符之间的空格
  2. 必须至少包含一个字母,可以包含字母和数字
  3. 最多7-15个字符(字母数字)
  4. 不能包含特殊字符
  5. 允许下划线
  6. 不知道该怎么做。任何帮助表示赞赏。谢谢。

    这是我正在使用的,但它允许字符之间的空格

    "(?=.*[a-zA-Z])[a-zA-Z0-9_]{1}[_a-zA-Z0-9\\s]{6,14}"
    

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

1 个答案:

答案 0 :(得分:4)

试试这个:

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

允许使用_,因为您在尝试时允许这样做。

所以基本上我使用三条规则。一个检查是否至少存在一个字母。 另一个检查字符串是否只包含alphas加_,最后我接受尾随空格,至少7个最多15个alpha。你的情况很好。坚持下去,你也会在这里回答问题:)

<强>故障:

    "
^           # 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)
"