我是regex的新手。
基本上,我需要在Java中验证密码,以满足以下要求:
密码必须至少包含6个字符characters.
要使密码有效,应满足以下4条验证规则中的任意3条:
例如:
Q145aqa
- OK,因为包含大写、小写和digit145AS$
- OK,因为包含大写、数字和非字母数字characters145234$
- Not OK,因为只包含数字和非字母数字字符,并且缺少另一个验证规则基本上,这就是我目前的正则表达式:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,20}$
我不知道如何将非字母数字字符的条件添加到表达式中,以及如何让正则表达式检查是否满足上述4个验证规则中的任何一个,以使密码有效?
发布于 2016-04-18 19:36:16
根据@kevin Esche的评论,你可以简单地使用字符串的.length()
方法来测试前两个验证。
为了使密码有效,您可以使用以下代码中的任何3个验证规则。
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
String password="a34A43";
boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());
if(hasUppercase)
count++;
if(hasLowercase)
count++;
Pattern p1 = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p1.matcher(password);
if(m.find())
count++;
Pattern p2 = Pattern.compile("\\d+", Pattern.CASE_INSENSITIVE);
Matcher m2 = p2.matcher(password);
if(m2.find())
count++;
if(count>=3)
System.out.println("Valid Password");
else
System.out.println("Invalid Password");
}
发布于 2018-08-19 21:11:20
这是一个有效的示例:
private final static String PASSWORD_PATTERN = "^[a-zA-Z0-9\\!\\$\\#\\%]{6,20}$";
https://stackoverflow.com/questions/36692333
复制相似问题