Validate Password in Java
Check if a password meets basic strength rules using regex.
IntermediateModule 4: String ProgramsExample 21 of 25
validate-password.java
1import java.util.Scanner;2import java.util.regex.Pattern;34public class Main {5 public static void main(String[] args) {6 Scanner sc = new Scanner(System.in);7 System.out.print("Enter password: ");8 String pwd = sc.nextLine();910 // At least 8 chars, one digit, one lower, one upper11 String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";12 boolean strong = Pattern.matches(regex, pwd);13 System.out.println(strong ? "Strong password" : "Weak password");14 sc.close();15 }16}
Output
Enter password: Abcdef1g Strong password
What's going on
We use lookahead-based regex to require digit, lowercase, uppercase, and minimum length.