2011-12-02 57 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