需要带有动态值的正则表达式

时间:2019-07-12 12:48:13

标签: java regex

我需要创建一个正则表达式,以匹配下面来自后端的动态值。

int passwordMaxLength = 10;
int passwordMinAlpha = 1;
int passwordMinCharType = 1;
int passwordMinLength = 5;
int passwordMinLower = 1;
int passwordMinNumeric = 1;
int passwordMinSpecial = 1;
int passwordMinUpper = 1;
String passwordNumberCharacters = "123";
String passwordSpecialCharacters = "@";
String passwordUpperCharacters = "ABC";

谢谢!

这是我到目前为止所拥有的:

String pattern1 = "^(?=(.*["+passwordUpperCharacters+"]){"+passwordMinUpper+",})(?=(.*[a-z]){"+passwordMinLower+",})(?=(.*["+passwordSpecialCharacters+"]){"+passwordMinSpecial+",})(?=(.*["+passwordNumberCharacters+"]){"+passwordMinNumeric+",})(*["+passwordUpperCharacters+""+passwordNumberCharacters+"]*[@]){"+passwordMinLength+","+passwordMaxLength+"}$";

1 个答案:

答案 0 :(得分:0)

正如建议的那样,单个正则表达式将首先很难制造,其次很难维护。 试想一下,如果您是项目新手并且必须修改您提供的正则表达式……说实话,这将是一场噩梦!

做到这一点的一种好方法是拥有一个可以相互独立检查所有约束的类。 您可以想象每个约束的方法。然后,在阅读时真的很容易理解,并且在任何约束更改下,您都可以轻松地做到这一点!

这是一个可以做到这一点的类的示例(目前仅检查大小和位数,但很容易添加验证)

public class PasswordChecker {

private int passwordMaxLength = 10;
private int passwordMinAlpha = 1;
private int passwordMinCharType = 1;
private int passwordMinLength = 5;
private int passwordMinLower = 1;
private int passwordMinNumeric = 1;
private int passwordMinSpecial = 1;
private int passwordMinUpper = 1;
private String passwordNumberCharacters = "123";
private String passwordSpecialCharacters = "@";
private String passwordUpperCharacters = "ABC";

public PasswordChecker() {
}

public boolean isValid(String password){
// here you can add many more functions !
    return hasValidLength(password) && hasValidNumberOfDigits(password);
}

private boolean hasValidLength(String password) {
    return password.length() <= passwordMaxLength;
}

private boolean hasValidNumberOfDigits(String password) {
    int count = 0;
    for (int i = 0, len = password.length(); i < len; i++) {
        if (Character.isDigit(password.charAt(i))) {
            count++;
        }
    }

    return count >= passwordMinNumeric;
}
}

然后您可以使用passwordChecker.isValid(password)

对其进行调用

然后,如果您想验证每个语句并返回密码中无效内容的完整说明,建议您为每个想要的验证返回一个具有布尔属性的对象,然后返回该对象,并且该对象将为每个验证携带确认是否可以,例如:

class PasswordValidation {

private String password;
private boolean hasMaximumLength;
private boolean hasMinimumNumberOfDigits;
// here add all of your validations ...
// also constructor and getters + setters
}

并且在PasswordChecker类中,您可以在方法中添加如下内容(最大长度的示例)

private PasswordValidator hasValidLength(String password, PasswordValidator validator) {
    validator.setHasMaximumLength(password.length() <= passwordMaxLength);
    return validator
}

并返回此validator

public boolean isValid(String password){
    PasswordValidator validator = new PasswordValidator(password);
    validator = hasValidLength(password, validator);
    validator = hasValidNumberOfDigits(password, validator);

    // here keep validating
    return validator;

}