2017-05-07 69 views
1

我刚刚创建此类密码验证Java的正则表达式表达式密码

/* 
*^      Start anchor 
* (?=.*[A-Z].*[A-Z])  Ensure string has two uppercase letters. 
* (?=.*[[email protected]#$&*])   Ensure string has one special case letter. 
* (?=.*[0-9].*[0-9])  Ensure string has two digits. 
* (?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters. 
* .{8}      Ensure string is of length 8. 
* $       End anchor. 
*/ 
public class PasswordUtils { 

    private static final String PWD_REGEX = "^(?=.*[A-Z].*[A-Z])(?=.*[[email protected]#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z])"; 

    /** 
    * Non instantiable. 
    */ 
    private PasswordUtils() { 
     throw new AssertionError("Non instantiable"); 
    } 

    public static boolean match (String pwd1, String pwd2) { 
     return StringUtils.equals(pwd1, pwd2); 
    } 

    public static boolean isStrong(String password){ 
     return password.matches(PWD_REGEX); 
    } 
} 

那么这Junit的,但它似乎PWD不符合要求的正则表达式

private final String PWD6 = "Pi89pR&s"; 

@Test 
public void testStrong() { 
    assertTrue(PasswordUtils.isStrong(PWD6)); 
} 
+4

它更容易不使用正则表达式。只需一次迭代字符串中的一个字符,计算大写字母,小写字母的数量等,然后确保计数符合您的标准。 –

回答

1

试试这个希望这将帮助你..

正则表达式:^(?=.*?[A-Z].*?[A-Z])(?=.*?[a-z].*?[a-z].*?[a-z])(?=.*?[\d].*?[\d])(?=.*?[^\w]).{8}$

^开始字符串。

2.(?=.*?[A-Z].*?[A-Z])积极向前看两个大写字母。

3.(?=.*?[a-z].*?[a-z].*?[a-z])积极向前看三个小写字母。

4.(?=.*?[\d].*?[\d])积极向前看两位数字。

5.(?=.*?[^\w])积极进取的外观对于非文字字符

6..{8}将完全匹配8个字符。

7.$字符串结束。

Regex code demo

1

试试这个:

(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=(?:.*[0-9]){2})(?=(?:.*[[email protected]#$&*]){1}).{8}

的基本思路是:

(?=(?:.*[GROUP]){NUMBER})

哪里GROUP是分组要匹配(即A-Z)和NUMBER是多少。

另请注意,如果要匹配NUMBER或更多出现的每个组,可以使用{NUMBER,}

https://regex101.com/r/JGtIkF/1