簡體   English   中英

找出上述條件的正則表達式

[英]Figuring out regex for the mentioned condition

我最近遇到了regex的概念,並准備僅使用String類的matches()length()方法中的regex來解決該問題。 問題與密碼匹配有關。以下是需要考慮的三個條件:

  • 密碼必須至少有八個字符。
  • 密碼僅由字母和數字組成。
  • 密碼必須至少包含兩位數字。

我能夠通過使用各種其他StringCharacter類方法來解決這個問題,但我只需要通過regex來完成它們。我嘗試過的方法可以幫助我處理大多數測試用例,但其中一些(測試用例)仍然失敗。因為,我正在學習regex實現,所以請幫助我解決我遺漏或做錯的事情。 以下是我嘗試過的:

public class CheckPassword {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your password:\n");
        String str1 = sc.next();
        //String dig2 = "\\d{2}";
        //String letter = ".*[A-Z].*";
        //String letter1 = ".*[a-z].*";
        //if(str1.length() >= 8 && str1.matches(dig2) &&(str1.matches(letter) || str1.matches(letter1)) )
          if(str1.length() >= 8 && str1.matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d{2,})(?=.*[0-9])[A-Z0-9a-z]+$"))
               System.out.println("Valid Password");
          else
               System.out.println("Invalid Password");

}
}

編輯

好的,所以我想出了第一個和第二個案例,只是我在附加第三個案例時遇到了問題,即包含至少 2 位數字。

 if(str1.length() >= 8 && str1.matches("[a-zA-Z0-9]*")) 
//works exclusive of the third criterion

您實際上可以在matches()使用單個正則表達式來驗證所有 3 個條件:

  • 密碼必須至少有八個字符,並且
  • 密碼僅由字母和數字組成- 在消費部分使用\\p{Alnum}{8,}
  • 密碼必須至少包含兩位數字- 使用(?=(?:[a-zA-Z]*\\d){2})正前瞻定位在開頭

三者結合:

.matches("(?=(?:[a-zA-Z]*\\d){2})\\p{Alnum}{8,}")

由於matches()方法默認錨定模式(即它需要完整的字符串匹配),因此不需要^$錨點。

詳情

  • ^ - 隱含在matches() - 字符串的開始
  • (?=(?:[a-zA-Z]*\\d){2}) - 一個正向前瞻( (?=...) ),需要正好存在以下兩個序列:
    • [a-zA-Z]* - 零個或多個 ASCII 字母
    • \\d - 一個 ASCII 數字
  • \\p{Alnum}{8,} - 8 個或更多字母數字字符(僅限 ASCII)
  • $ - 隱含在matches() - 字符串的結尾。

好的,謝謝@TDG 和 M.Aroosi 給予您寶貴的時間。 我已經找到了解決方案,這個解決方案滿足所有情況

 // answer edited based on OP's working comment.
 String dig2 =  "^(?=.*?\\d.*\\d)[a-zA-Z0-9]{8,}$";
 if(str1.matches(dig2))
      {
       //body          
      }

暫無
暫無

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

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