简体   繁体   English

正则表达式Java可选字符

[英]Regex Java optional characters

I have a this regex; 我有一个正则表达式;

("(?=.*[az]).*") ("(?=.*[0-9]).*") ("(?=.*[AZ]).*") ("(?=.*[!@#$%&*()_+=|<>?{}\\\\[\\\\]~-]).*")

that checks a password with requirements: length =8, then three of the following - a lowerCase, an upperCase, a digit, special character. 该密码将检查密码是否符合要求:长度= 8,然后是以下三个字符-lowerCase,upperCase,数字,特殊字符。 3 of the above 4 + length of 8 is required. 以上4个中的3个+长度为8。

What I have works until there is a space in the password, then it prints the wrong message. 我的工作原理是直到密码中没有空格,然后它才输出错误的消息。 In other-words, how do I include whitespace in my list of special characters, thanks! 换句话说,我如何在特殊字符列表中包含空格,谢谢!

You can try this out: 您可以尝试以下方法:

String password = "pA55w$rd";

int counter = 0;

if(password.length() >= 8)
{
    Pattern pat = Pattern.compile(".*[a-z].*"); // Lowercase
    Matcher m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*[0-9].*"); // Digit
    m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*[A-Z].*"); // Uppercase
    m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*\\W.*"); // Special Character
    m = pat.matcher(password);
    if(m.find()) counter++;

    if(counter == 3 || counter == 4)
    {
        System.out.println("VALID PASSWORD!");
    }
    else
    {
        System.out.println("INVALID PASSWORD!");
    }
}
else
{
    System.out.println("INVALID PASSWORD!");
}

There are two cases: either it matches the length required, or not. 有两种情况:要么与所需长度匹配,要么不匹配。

If it does match the length, it checks each of the 4 cases once, and increments a counter every time it does. 如果它与长度匹配,则会对这4种情况中的每一种进行一次检查,并且每次都增加一个计数器。 Since you want it to match 3 or 4 of the cases, I put an if-else case over there. 由于您希望它匹配3或4种情况,因此我在此处放置了if-else情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM