0

I try to use the following expression to check whether the password is a combination of number and letter despite the order of letter and number

password.matches("[a-zA-z]{1,}[0-9]{1,}")

but the above code would check with the order letter goes first, then number comes later

like the password would be acceptable if the password looks like "hello1213" and "123hello"

Kesong Xie
  • 1,316
  • 3
  • 15
  • 35
  • possible duplicate of [Password REGEX with min 6 chars, at least one letter and one number and may contain special characters](http://stackoverflow.com/questions/7844359/password-regex-with-min-6-chars-at-least-one-letter-and-one-number-and-may-cont) –  Apr 09 '14 at 19:04

1 Answers1

4

Simply this will do, if you do not have any plan for mandatory letter, or digit:

password.matches("^[a-zA-Z0-9]+$");

However, if you have plan to have at least one digit, and one letter, then try this one:

password.matches("^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]+$");

(?=.*[0-9]) is positive lookahead that check that the input has a minimum one digit, and the similar fashioned lookahead (?=.*[a-zA-Z]) checks for a minimum letter.

Note: since you are using matches(), you can ignore the anchors ^ $ from the regex. Those are required when you'll do matching through Pattern class.

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85