0

I must create a java program to check if the password is valid or not based on these conditions:

  • to be at least 5 chars long or at most 12 chars long
  • to start with an uppercase letter
  • to end with two different digits
  • to include at least one special character from the following: ! " # $ % & ' ( ) * + -
  • to include at least one lowercase letter

This is what I have written so far, and I want to know what's the regular expression to check the second condition (that the password must end with 2 different digits) ?

import java.util.Scanner;

public class PasswordValidation {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Please enter a password");
        
        String password = sc.next();

        if (isValid(password)) {
   
            System.out.println("OK");
        } else {
  
            System.out.println("NO");
        }
        
    }

        public static boolean isValid (String password) {
            return password.matches ("^[A-Z](?=.*[a-z])(?=.*[!#$%&'()+-]).{5,12}$");
        }
        

}

1
  • 1
    If this is for homework, fine. But DO NOT IMPOSE RESTRICTIONS ON PASSWORDS LIKE THIS. It's absolutely unnecessary, annoying, and there is no security basis for this whatsoever. Passwords need LENGTH, not random bullshit or weird, arbitrary constraints such as "ending in two different digits". If you want to enforce that a letter, number and symbol are all used, fine. But these restrictions are going to only hurt your users instead of help them. The best way to make users have good passwords is to enforce a minimum length of 9 or 10, which is a fair bit of entropy. Commented Nov 28, 2020 at 10:02

1 Answer 1

3

Try using this regex pattern:

^(?=.*[a-z])(?=.*[!"#$%&'()*+-])[A-Z].{2,9}(\d)(?!\1)\d$

Java code:

String password = "Apple$123";
if (password.matches("(?=.*[a-z])(?=.*[!\"#$%&'()*+-])[A-Z].{2,9}(\\d)(?!\\1)\\d")) {
    System.out.println("MATCH");
}

This prints MATCH.

Here is an explanation of the regex pattern:

^                         from the start of the password
    (?=.*[a-z])           assert that a lowercase letter be present
    (?=.*[!"#$%&'()*+-])  assert that a special character be present
    [A-Z]                 password starts with uppercase letter
    .{2,9}                followed by any 2 to 9 characters (total 5 to 12)
    (\d)                  2nd to last character is any digit
    (?!\1)\d              last character is any digit other than previous one
$                         end of the password
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.