Regex match a strong password with two or more special characters

最后都变了- 提交于 2019-12-05 01:20:45
/^(?=(?:.*[a-z]){2})(?=(?:.*[A-Z]){2})(?=(?:.*\d){2})(?=(?:.*[!@#$%^&*-]){2}).{15,}$/

Your lookaheads are wrong. The pattern

(?=.{2,}[class])

means to match 2 or more characters (no matter what characters), then followed by 1 character of the desired class. This is entirely different from "2 or more character of the desired class" you specified.

To correctly test if a character of desired class is in the text, use

(?=.*[class])

and since you want to check it twice, repeat the pattern

(?=.*[class].*[class])
# equivalent to (?=(?:.*[class]){2})

I'm not sure a single regexp is the way to go for this test.

Personally i'd implement it something like this: (treat as pseudo code, i haven't tested it)

function testPassword(pw) {
    var len = pw.length;
    if(len < 15) return false;
    if(pw.replace(/[a-z]/,'').length > len - 2) return false;
    if(pw.replace(/[A-Z]/,'').length > len - 2) return false;
    if(pw.replace(/[0-9]/,'').length > len - 2) return false;
    if(pw.replace(/[!@#$%^&*-]/,'').length > len - 2) return false;
    return true;
}

There are some good explanations already, so I'm just piling on ...

/^
(?= .{15} )
(?= (?:.*[[:lower:]]){2} )
(?= (?:.*[[:upper:]]){2} )
(?= (?:.*[[:digit:]]){2} )
(?= (?:.*[!@#$%^&*-]){2} )
/x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!