2012-12-17 182 views
1

我需要使用Java驗證密碼字符串。這是驗證的要求:用於驗證的正則表達式

  • 至少1號
  • 至少1字母字符
  • 至少1個字符從集@#$%^ & *()_ + = - 〜` ] [{};':「/> ?, <
  • 8〜20個字符

擰周圍和敲打我的頭到壁幾次後,我想出了這個正則表達式

if (!password.matches("^(?=.+[0-9])(?=.+[a-zA-Z])(?=.+[\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E])[0-9a-zA-Z\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E]{8,20}$")) { 

} 

這看起來太可怕和瘋了。有沒有更好的方法來完成這個任務?

+0

試試'[A-ZA-Z] + \\ d +!@#$%^&*()] +'你可能要引用特殊字符,如果他們有特殊的含義,這只是我的頭頂... – Thihara

+0

可能重複的[正則表達式密碼驗證](http://stackoverflow.com/questions/2370015/regular-expression-for-password-validation ) –

回答

3

我推薦使用正則表達式來表達他們最擅長的事情,但是使用正則表達式來處理正則表達式並不好。像這樣的東西。 (對不起,我沒有測試此代碼,但它應該給,即使我犯了一個錯誤,它不會跑的想法。)

Pattern special_chars = Pattern.compile("[[email protected]#$%^&*()_+=-~`\][{};':\"/.>?,<]"); 
Pattern number_chars = Pattern.compile("[0-9]"); 
Pattern letter_chars = Pattern.compile("[a-zA-Z]"); 

boolean valid; 

valid = (special_chars.matcher(password).find() && 
     number_chars.matcher(password).find() && 
     letter_chars.matcher(password).find() && 
     8 <= password.length() && password.length() <= 20); 
1

隨着番石榴CharMatcher

// at least 1 number 
CharMatcher.inRange('0', '9').countIn(password) >= 1 && 
// at least 1 alphabet character 
CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).countIn(password) >= 1 && 
// at least 1 character from set [email protected]#$%^&*()_+=-~`][{};':"/.>?,< 
CharMatcher.anyOf("[email protected]#$%^&*()_+=-~`][{};':\"/.>?,<").countIn(password) >= 1 && 
// 8 to 20 characters 
password.length() >= 8 && password.length() <= 20 

這是假定你想拉丁字母

+0

非常好的圖書館,確實如此。但是爲我的項目添加1個額外的lib需要很多討論。謝謝,anw:D –