Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password check using regex in Java

Tags:

java

regex

My application has a feature to check password. I need to get this scenario:

password length 10 ~ 32 .

It has to be a combination of either:

  • character and numbers
  • characters and special characters
  • numbers and special characters

Current code in application:

private boolean isSpecialMixedText(String password)
{
    String number = "[0-9]";
    String english = "[a-zA-Z]";
    String special = "[!@#\\$%^&*()~`\\-=_+\\[\\]{}|:\\\";',\\./<>?£¥\\\\]";

    Pattern numberPattern = Pattern.compile(number);
    Matcher numberMatcher = numberPattern.matcher(password); 

    Pattern englishPattern = Pattern.compile(english);
    Matcher englishMatcher = englishPattern.matcher(password);

    Pattern specialPattern = Pattern.compile(special);
    Matcher specialMatcher = specialPattern.matcher(password);
    return numberMatcher.find() && englishMatcher.find() || specialMatcher.find();
}

Please help me get the combination working

like image 331
Sunil Avatar asked Mar 05 '26 16:03

Sunil


1 Answers

Actually, the regexes look fine. The problem is in this statement:

return numberMatcher.find() && englishMatcher.find() || 
       specialMatcher.find();

It actually needs to be something like this:

boolean n = numberMatcher.find();
boolean e = englishMatcher.find();
boolean s = specialMatcher.find();
return (n && e) || (n && s) || (e && s);

And I agree with @adelphus' comment. Your rules for deciding what passwords are acceptable are very English-language-centric.

like image 158
Stephen C Avatar answered Mar 07 '26 07:03

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!