Kesong Xie
Kesong Xie

Reputation: 1396

how to use regex to check the password contains letter and number

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"

Upvotes: 0

Views: 1442

Answers (1)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

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.

Upvotes: 4

Related Questions