简体   繁体   中英

Regular Expression in JAVA in making a password

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){

You can assert 2 lowercase chars az between only digits, and then match 10 times either az or a digit.

^(?=\d*[a-z]\d*[a-z]\d*$)[a-z\d]{10}$

The pattern matches:

  • ^ Start of string
  • (?=\\d*[az]\\d*[az]\\d*$) Positive lookahead, assert 2 chars az between optional digits
  • [az\\d]{10} Repeat 10 times matching either a char az or a digit
  • $ End of string

Regex demo

In Java with double escaped backslashes

String regex = "^(?=\\d*[a-z]\\d*[a-z]\\d*$)[a-z\\d]{10}$";

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM