Regex Password Validation - 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.
到目前为止,这是我的尝试:
1 2 3 | function validate(password) { return /^[A-Za-z0-9]{6,}$/.test(password); } |
到目前为止,要做的是确保每个字符都是字母数字,并且密码至少有6个字符。在这方面似乎工作得很好。
我陷入了这样的境地:它要求有效密码至少有一个小写字母、一个大写字母和一个数字。如何使用单个正则表达式与前面的需求一起表示这些需求?
我可以在JavaScript中很容易地做到这一点,但我希望通过一个正则表达式来实现这一点,因为这正是测试的问题所在。
您需要使用lookaheads:
1 2 3 | function validate(password) { return /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])[A-Za-z0-9]{6,}$/.test(password); } |
说明:
1 2 3 4 5 6 | ^ # 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 lower 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 |