Password Confirmation Using Regular Expression

Below is a regular expression that validates my passwords:

(((?=.*\\d{2,20})(?=.*[a-z]{2,20})(?=.*[A-Z]{3,20})(?=.*[@#$%!@@%&*?_~,-]{2,20})).{9,20}[^<>'\"])

Basically, I want it to contain all the above characters in the password. But he needs these characters in sequence, for example, he checks 23aaAAA@!, but does not confirm a2@!AAAa.

+4
source share
2 answers

Just add nested capture groups to save character checking not strictly as a sequence. The regular expression can also be simplified as follows (without additional groups):

(?=(?:.*[0-9]){2,20})
(?=(?:.*[a-z]){2,20})
(?=(?:.*[A-Z]){3,20})
(?=(?:.*[@#$%!&*?_~,-]){2,20})
.{9,20}
[^<>'\"] # This matches also the newline char, i don't think you really want this...

In java use it like this:

String regex = "(?=(?:.*[0-9]){2,20})(?=(?:.*[a-z]){2,20})(?=(?:.*[A-Z]){3,20})(?=(?:.*[@#$%!&*?_~,-]){2,20}).{9,20}[^<>'\"]";
String password = "23aaA@AA!@X"; // This have to be 10 chars long at least, no newline

if (password.matches(regex))
    System.out.println("Success");
else
    System.out.println("Failure");

For regular expression, a password is required with (everything is not strictly in sequence):

  • (?=(?:.*[0-9]){2,20}): 2 numbers
  • (?=(?:.*[a-z]){2,20}): 3 lowercase lettes
  • (?=(?:.*[A-Z]){3,20}): 3
  • (?=(?:.*[@#$%!&*?_~,-]){2,20}): 2
  • .{9,20}: 9 . 20
  • [^<>'\"]: char, (<, >, ', ") (: )

, min/max 10/21, , - regex 9 20.

Regex -

+2

, . .

"a2 @! AAAa" , 2 .

, . .

public class Constraint {

    private Pattern pattern;
    public String regexp = "";
    public int mincount=2;
    public int maxcount=6;

    public Constraint(String regexp, int mincount, int maxcount) {
        this.mincount=mincount;
        this.maxcount=maxcount;
        pattern = Pattern.compile(regexp);
    }

    public boolean fit(String str)
    {
        int count = str.length() - pattern.matcher(str).replaceAll("").length();
        return count >= mincount && count <= maxcount;
    }

    @Override
    public String toString() {
        return pattern.toString();
    }
}


public class Test {

    static Constraint[] constraints = new Constraint[] {
            new Constraint("[a-z]",2,20),
            new Constraint("[A-Z]",2,20),
            new Constraint("\\d",2,20),
            new Constraint("["+Pattern.quote("@#$%!@@%&*?_~,-")+"]",2,20),
            new Constraint("[<>'\\\"]",0,0)
    };

    public static boolean checkit(String pwd)
    {
        boolean ok=true;
        for (Constraint constraint:constraints)
        {
            if (constraint.fit(pwd)==false)
            {
                System.out.println("match failed for constraint "+constraint);
                ok=false;
            }
        }
        return ok;
    }

    public static void main(String[] args) {
        checkit("23aaAAA@!");
        checkit("a2@!AAAa");
    }
}
0

Source: https://habr.com/ru/post/1617586/


All Articles