2016-06-28 22 views
-2

我已經提到,Srinivas的答案進行密碼驗證。 最小8字符正則表達式,1號,1個字母和一個特殊字符是正則表達式來檢查密碼驗證

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[[email protected]$!%*#?&])[A-Za-z\[email protected]$!%*#?&]{8,}$" 

利用該正則表達式,我只能使用下面的特殊字符。 $ @ $!%*#? &。 因此,如果我使用dheepan~123dheepan.123,則驗證失敗。我怎樣才能讓所有的特殊字符?

+1

*「所有特殊字符」*?定義它們,你有你的答案。 –

+1

這意味着你不明白給出的解決方案。只需將這些特殊字符添加到你的角色類。 – anubhava

+0

將它們添加到[$ @ $!%*#?&]中。加點時記得給斜線(\。)。用「〜」 - 我不知道是否需要斜線,但你可以試試。 –

回答

1

您可以允許所有特殊字符使用\W,但我不知道你真的想這樣做......總之:

^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W])[\w\W]{8,}$ 
+0

僅供參考:'[\ w \ W]'相當於''',因爲'\ W'是'^ \ w' – Cam

+2

@Cam:不是,'.'與默認情況下不匹配換行符。 – Toto

+0

公平點,@Toto;默認情況下'.'與linebreaks不匹配。所以'.' ='[\ w \ W]' - '\ n'。雖然'/./ s' ='/ [\ w \ W] /' – Cam

0

你可以關注@托馬斯的解決方案來定義的符號,所有非字詞\W,但請注意這包括空格。如果用戶的密碼中有一個換行符,他們幾乎肯定會被鎖定。

對於密碼,通過描述準確描述哪些字符是值得的。如果你想使用代字號~或句號.,只需按照@anubhava的建議將它們添加到正則表達式的字符類中。

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[[email protected]$!%*#?&])[A-Za-z\[email protected]$!%*#?&]{8,}$" 
//        ^     ^
//         \__add them here __/_________ 
//          | |     | | 
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[[email protected]$!%*#?&~\.])[A-Za-z\[email protected]$!%*#?&~\.]{8,}$" 

要使用正則表達式負責任的,我們的目標應該是要了解什麼是引擎蓋下回事。以下是您正在使用的正則表達式的工作原理的演練。

^ 
// From the beginning of your string 

(?=.*[A-Za-z]) 
// Look ahead       (?=  ) 
// any number of chars     .* 
// Until you find an alpha character [A-Za-z] 

(?=.*\d) 
// Look ahead       (?=  ) 
// any number of chars     .* 
// Until you find a digit    \d 

(?=.*[[email protected]$!%*#?&]) 
// Look ahead       (?=  ) 
// any number of chars     .* 
// Until you find one of these chars [[email protected]$!%*#?&] 

[A-Za-z\[email protected]$!%*#?&]{8,} 
// Find any of these characters   [A-Za-z\[email protected]$!%*#?&] 
// 8 or more times      {8,}