【问题标题】:Regex Password Validation - Codewars [duplicate]正则表达式密码验证 - Codewars [重复]
【发布时间】:2015-06-10 11:49:59
【问题描述】:

免责声明:这是一个Codewars 问题。

您需要编写正则表达式来验证密码以确保它 符合以下条件:

  • 至少六个字符
  • 包含小写字母
  • 包含一个大写字母
  • 包含一个数字

有效密码将只 字母数字字符。

到目前为止,这是我的尝试:

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

到目前为止,它所做的是确保每个字符都是字母数字,并且密码至少包含 6 个字符。在这些方面它似乎工作正常。

我被困在要求有效密码至少包含一个小写字母、一个大写字母和一个数字的部分。如何使用单个正则表达式将这些要求与之前的要求一起表达?

我可以在 JavaScript 中轻松做到这一点,但我希望仅通过正则表达式来做到这一点,因为这是问题正在测试的内容。

【问题讨论】:

标签: javascript regex


【解决方案1】:

您需要使用前瞻:

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

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 2016-06-03
    • 2016-10-30
    • 2016-04-15
    • 2014-12-12
    • 2016-10-09
    • 2016-04-12
    • 2014-12-16
    相关资源
    最近更新 更多