2011-12-02 67 views
5

需要一个正则表达式来验证用户名,其中:需要的正则表达式来验证用户名

  1. 应该允许尾随空格,但不是空格字符之间
  2. 必须至少包含一个字母,可以包含字母和数字
  3. 7-15字元(字母数字)
  4. 不能包含特殊字符
  5. 下划线允许

不知道如何做到这一点。任何帮助表示赞赏。谢谢。

这是我用的是什么,但它可以让人物之间的空间

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

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

+0

为什么你必须使用一个单一的正则表达式的呢?通常几行清晰的代码比单个扭曲的正则表达式更好。允许尾随空格似乎很奇怪;他们实际上是用户名的一部分,还是被忽略?你真的想把“弗雷德”和“弗雷德”当作截然不同的东西吗?尾随空格是否计算在7-15的最大长度?一个用户名必须至少是* 7个字符,或者是否有一个可变的最大长度,可以是7到15之间的任何值(以及基于什么)?什么是“特殊字符”? “123_456”是否有效(即,出于规则2的目的,是否将下划线计为一个字母)? –

回答

4

试试这个:

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

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

所以基本上我使用三条规则。一个用于检查是否存在至少一个字母。 另一个检查字符串是否只包含alpha和_,最后我接受尾随空格,并且至少有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) 
" 
+0

嗨,你提供的上述表达式仍然允许字符间的空格 – 1078081

+0

@ user1078081是吗?你能解释一下这可能吗? – FailedDev

+0

这显示了一个无效的转义序列(有效的转义序列是\ b \ t \ n \ f \ r \“\'\)语法错误模式我该如何解决它 – 1078081