Regex expression for password rules

后端 未结 2 1423
难免孤独
难免孤独 2020-12-07 00:02

I have a requirement for password rules. Following are the rules.

The password must follow the following guidelines:

  • Be at least eight characters long<
2条回答
  •  隐瞒了意图╮
    2020-12-07 00:48

    Here's how I would do it:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class ValidatePassword
    {
        public static void main (String[] args)
        {
            String pw = "abaslkA3FLKJ";
    
            // create an array with 4 regex patterns
    
            Pattern [] patternArray = {
                Pattern.compile("[a-z]"),
                Pattern.compile("[A-Z]"),
                Pattern.compile("[0-9]"),
                Pattern.compile("[&%$#]")
            };
    
            int matchCount = 0;
    
            // iterate over the patterns looking for matches
    
            for (Pattern thisPattern : patternArray) {
                Matcher theMatcher = thisPattern.matcher(pw);        
                if (theMatcher.find()) {
                    matchCount ++;
                }
            }
    
            if (matchCount >= 3) {
                System.out.println("Success");
            }
    
            else {
                System.out.println("Failure: only " + matchCount + " matches");
            }
        }
    }
    

    I only added a few special characters to the 4th pattern... You'll have to modify it for your needs. You may need to escape certain characters with a backslash. You may also want to add other constraints like checking for no spaces. I'll leave that up to you.

提交回复
热议问题