密码使用Regex验证

时间:2015-11-26 09:40:02

标签: regex validation

以下是验证我的密码的正则表达式:

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

基本上我想要的是它包含密码中所有上面给出的字符。但它需要顺序的那些字符,例如 它验证23aaAAA@!,但不验证a2@!AAAa

2 个答案:

答案 0 :(得分:2)

只需添加嵌套捕获组即可将字符验证严格保留为序列。正则表达式也可以简化如下(没有额外的组):

(?=(?:.*[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...

在java中使用它如下匹配:

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");

正则表达式需要一个密码(所有不严格按顺序):

  • (?=(?:.*[0-9]){2,20}):2个数字
  • (?=(?:.*[a-z]){2,20}):3个小写字母
  • (?=(?:.*[A-Z]){3,20}):3个大写字母
  • (?=(?:.*[@#$%!&*?_~,-]){2,20}):字符组中的2个符号
  • .{9,20}:最小长度为9,最多为20
  • [^<>'\"]:一个不在(<>'"中的字符(注意:这也符合换行符)< / LI>

所以min / max实际上是10 / 21,但最后一个状态也匹配换行符,因此在线正则表达式演示中,可见字符将是在920之间。

Regex在线演示here

答案 1 :(得分:0)

我不会尝试构建单个正则表达式,因为没有人能够再次阅读或更改此表达式。这很难理解。

“a2 @!AAAa”永远不会验证,因为它需要2位数。

如果您需要密码,则该密码包含组中的minmuum和最大字符数。简单算一下。

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");
    }
}