2017-05-07 65 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