Kushal
Kushal

Reputation: 47

password generation in java using regex

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Generate your Security Code ");
        String password=sc.next();

        if(password.length()>=8)
        {
            Pattern letter = Pattern.compile("[a-z]{1}[A-z]{1}");
            Pattern digit = Pattern.compile("[0-9]");
            Pattern special = Pattern.compile ("[@#*]{1}");


               Matcher hasLetter = letter.matcher(password);
               Matcher hasDigit = digit.matcher(password);
               Matcher hasSpecial = special.matcher(password);

               if(hasLetter.find() && hasSpecial.find() &&hasDigit.find()){
                   System.out.println("Security Code Generated Successfully");
               }

        }
        else{
        System.out.println("Invalid Security Code, Try Again!");

        }
}
}

I wrote a code for password generation but one test case is failing,the digits in password are not compulsory how do i do it?

List item

Upvotes: 1

Views: 228

Answers (1)

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

If you want to change the regex for optional digit then add a * . Another way around is to use || instead of &&

if(hasLetter.find() && hasSpecial.find() ||hasDigit.find()){
        System.out.println("Security Code Generated Successfully");
      }

Upvotes: 1

Related Questions