I am looking to write a code to generate password using an input regex. I know we can validate a password against a regex but can we reverse engineer it and create a password ?
For example, if the regex is ^.*(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@!#$%^&*()+=]).*$ can we write a code in java to generate a random password that meets the requirement ? It should work for any regex.
Right now I have a very simple one. But I want to improve this
    // Method to generate a random alphanumeric password of a specific length
private static String generateRandomPassword(int len) {
    // ASCII range – alphanumeric (0-9, a-z, A-Z)
    final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    SecureRandom random = new SecureRandom();
    return IntStream.range(0, len)
            .map(i -> random.nextInt(chars.length()))
            .mapToObj(randomIndex -> String.valueOf(chars.charAt(randomIndex)))
            .collect(Collectors.joining());
}
 
    