簡體   English   中英

使用正則表達式在 Java 中驗證密碼

[英]Password validation in Java using RegEx

我需要一個正則表達式來檢查密碼是否包含:

  • [1,6] 大寫/小寫字符
  • [1,10] 位數字
  • [0,1] 特殊字符

我嘗試了多種方法,但沒有成功。 我不知道我是否可以使用正則表達式進行驗證。 最准確的模式是: ^(?=(.*[a-zA-Z]){1,6})(?=(.*[0-9]){1,10})(?=(.*[.@#$%^&*()\-__+,]){0,1})

但是當我有超過 6 個字符、10 個數字或 1 個特殊字符時,它就不能正常工作了。

誰能幫幫我?

我可能不會使用單一的正則表達式模式,而是會使用多個檢查。 例如:

String password = "ABC123@";
int numChars = password.replaceAll("(?i)[^A-Z]+", "").length();
int numDigits = password.replaceAll("\\D+", "").length();
int numSpecial = password.replaceAll("[^!@#$%^&*()_+.-]", "").length();

if (numChars >=1 && numChars <= 6 && numDigits >= 1 && numDigits <= 10 &&
    numSpecial <= 1) {
    System.out.println("password is valid");
}
else {
    System.out.println("password is invalid");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM