Reputation: 31
I have a question. My goal is to make a password; the password must consist of two lowercase letters and 8 digits from 0-9. I have made a code for this using regular expression but the problem is that it exceeds the overall number of that the password must be which is 10 but my code here doesn't really match actually.
Here is my code:
System.out.print("Password: ");
Scanner pass=new Scanner(System.in);
String password=pass.next();
String password_regex="(?=.*[0-9])(?=.*[a-z])(?=\\S+$).{8,}";
boolean password_result=password.matches(password_regex);
if(password_result){
Upvotes: 1
Views: 187
Reputation: 44335
Regular expressions are heavyweight and are hard to read. Highly complex ones are prone to mistakes—mistakes which the compiler cannot catch. You might understand the regex now, but will you understand it when you come back to the code in six months? Will other people understand it?
Unless you have a specific requirement to do the entire check with exactly one regular expression, there are better choices than regular expressions. You can check the characters themselves:
boolean hasTwoLetters =
(password.codePoints().filter(Character::isLetter).count() == 2);
boolean hasEightDigits =
(password.codePoints().filter(Character::isDigit).count() == 8);
boolean passwordValid = hasTwoLetters && hasEightDigits;
Just because it looks longer than a single regex match doesn’t mean it will take longer. Regular expression engines are complex libraries with a lot of code under the hood. This approach just looks at the password characters one at a time and counts them.
For more information, see:
Upvotes: 0
Reputation: 163362
You can assert 2 lowercase chars a-z between only digits, and then match 10 times either a-z or a digit.
^(?=\d*[a-z]\d*[a-z]\d*$)[a-z\d]{10}$
The pattern matches:
^
Start of string(?=\d*[a-z]\d*[a-z]\d*$)
Positive lookahead, assert 2 chars a-z between optional digits[a-z\d]{10}
Repeat 10 times matching either a char a-z or a digit$
End of stringIn Java with double escaped backslashes
String regex = "^(?=\\d*[a-z]\\d*[a-z]\\d*$)[a-z\\d]{10}$";
Upvotes: 2