gpt4 book ai didi

javascript - 正则表达式密码验证 - Codewars

转载 作者:行者123 更新时间:2023-11-28 11:07:03 25 4
gpt4 key购买 nike

免责声明:这是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 中完成此操作,但我希望仅通过正则表达式来完成此操作,因为这就是问题正在测试的内容。

最佳答案

您需要使用前瞻:

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 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

关于javascript - 正则表达式密码验证 - Codewars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29465214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com