2015-04-06 75 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