0

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 pattern = /(=?.{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?

stema
  • 90,351
  • 20
  • 107
  • 135
Đinh Hồng Châu
  • 5,300
  • 15
  • 53
  • 90
  • This answer might help you: http://stackoverflow.com/questions/11992544/validating-password-using-regex/11992602 – netdigger Aug 16 '12 at 19:11

2 Answers2

2

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;
}
user562374
  • 3,817
  • 1
  • 22
  • 19
0

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.

Anon.
  • 58,739
  • 8
  • 81
  • 86