2015-04-06 113 views
1

免責聲明:這是一個Codewars問題。正則表達式驗證密碼 - Codewars

You need to write regex that will validate a password to make sure it meets the following criteria:

  • At least six characters long
  • contains a lowercase letter
  • contains an uppercase letter
  • contains a number

Valid passwords will only be alphanumeric characters.

到目前爲止,這是我的嘗試:

function validate(password) { 
    return /^[A-Za-z0-9]{6,}$/.test(password); 
} 

這樣做有什麼到目前爲止是確保每個字符是字母數字,該密碼至少有6個字符。它似乎在這些方面正常工作。

我卡在部分地方需要一個有效的密碼至少有一個小寫字母,一個大寫字母和一個數字。我如何使用單個正則表達式來表達這些要求以及以前的要求?

我可以很容易地做到這一點在JavaScript,但我希望做它通過一個正則表達式單單因爲這是問題是什麼測試。

+2

有可能一打就這些問題已經SO,如果不是更多。搜索他們。 – 2015-04-06 04:20:39

+1

https://www.google.co.in/search?q=ypeError:+expected+a+character+buffer+object&ie=UTF-8&sa=Search&channel=fe&client=browser-ubuntu&hl=zh-CN&gws_rd=cr,ssl&ei=EOchVZS3JYLv8gXJkoHwCA#通道= FE&HL = EN-IN&q =網站:stackoverflow.com +正則表達式+密碼+驗證 – 2015-04-06 04:20:59

回答

7

您需要使用向前看符號:

function validate(password) { 
    return /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])[A-Za-z0-9]{6,}$/.test(password); 
} 

說明:

^    # start of input 
(?=.*?[A-Z]) # Lookahead to make sure there is at least one upper case letter 
(?=.*?[a-z]) # Lookahead to make sure there is at least one upper case letter 
(?=.*?[0-9]) # Lookahead to make sure there is at least one number 
[A-Za-z0-9]{6,} # Make sure there are at least 6 characters of [A-Za-z0-9] 
$    # end of input 
+2

可怕你如何快速得到這個答案......我只是根據你的速度,你投票了! – 2015-04-06 04:10:03

+1

似乎工作。介意解釋一下? – Shashank 2015-04-06 04:14:18

+0

@TimBiegeleisen:非常感謝。 Shashank:我在我的回答中添加了解釋。 – anubhava 2015-04-06 04:17:19