开发者

Regex pattern for validating password

I am working with a small issue, but I don't know how to solve it clearly. I have to validate a generated password, with some constraints:

  • password length: [8, 24]
  • password contains
    • at least 1 lower case character
    • at least 1 upper case character
    • at least 1 digit
    • at least 1 special character (printable based on ASCII code)

I've used Regex pattern, but it didn't work correctly with both cases: valid and invalid.

The first RegEx pattern:

def pattern = /(=?.{8,24})((:?[a-z]+)(:?[0-9]+)(:?[A-Z]+)(:?\W+))/ 

can check all invalid passwords but not for the valid one.

The second RegEx pattern:

def patt开发者_开发知识库ern = /(=?.{8,24})((:?[a-z]*)(:?[0-9]*)(:?[A-Z]*)(:?\W*))/ 

can check all valid passwords but not for the invalid one.

I am new to Groovy, so I don't know how to create the correct RegEx pattern to solve this. Could you please help me?


Regex is not a solution to everything, and trying to come up with a single regex for a given problem is often wasting brain cycles. Just separate it out into multiple tests, for example (this Perl-like pseudo code, but you should be able to transform that to the language you are using):

sub valid_pw
{
    return false if (length($_) < 8 || length($_) > 24);
    # don't use [a-z], it makes for nasty surprises in e.g. fi_FI
    return false if (!/[[:lower:]]/);
    return false if (!/[[:upper:]]/);
    return false if (!/[[:digit:]]/);
    return false if (!/[[:print:]]/);
    return true;
}


Why do you need a single regex for this? (also why are you placing a maximum length on the password, which is another discussion)

/^.{8,24}$/
/[a-z]/
/[A-Z]/
/\d/
/[^\d\w]/

I guess you could combine them using lookaheads (say /(?=.*[a-z])(?=.*[A-Z])...), but if you do it's probably a really good idea to comment it heavily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜