Jordan Jason
Jordan Jason

Reputation: 13

My code with matches() is not working. Why is it not working?

I am trying to create a small program that reads a password and determines if it is a password you can use. I was using matches() to see if it has at least one letter (uppercase or lowercase) and one digit as well as be 6 characters long. I try to use matches like this:

if ( passwordLength >= 6 
   && password.matches("[A-Za-z]") 
   && password.matches("\\d")
) {
    System.out.println("Valid Password.");
} 
else {
    System.out.println("Invalid Password.");
}

Im not sure what i am doing wrong. Please help.

Upvotes: 0

Views: 83

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

matches function should try to match the whole string using the regex we gave. So instead of using two or more matches functions for condition checking, you may use a single one with a complex regex. And also it seems like your password would contain not only digits or letters but also some other characters too.

string.matches("^(?=.*[a-zA-Z])(?=.*\\d).{6,}$");
  • (?=.*[a-zA-Z]) Positive lookahead which asserts that the string going to be matched must contain atleast one letter.

  • (?=.*\\d) asserts it must contain atleast one digit.

  • .{6,} ensures that the length must be atleast 6 and atmost any..

For the length to be exactly 6 then change .{6,} in the above to .{6}

DEMO

Upvotes: 1

Erik Pragt
Erik Pragt

Reputation: 14617

There are a couple of things wrong with your code:

  • Your regex is wrong. You are only matching on 1 character, so you should change the [a-z] to [a-z]+.
  • You are matching on 'it should be bigger than 6, should be a character, AND it should be a number. That's different from your requirement.

Upvotes: 0

Matt O
Matt O

Reputation: 1346

It looks like you're misinterpreting the matches function, which matches over the entire input, while you're expecting it to return true if a substring matches. As others suggested, you'll need to use a single regex and matches() call since you're asking if the string is a single character AND a number (which would never be true).

Another important point, though it may not be important to you, is that a password should never be stored as a String object since they're immutable and can persist long enough for something else to come along and read it. More on that here.

Upvotes: 0

Related Questions