簡體   English   中英

檢查字符串是否以 java 中的正則表達式以 2 個不同的數字結尾

[英]Check if string ends with 2 different digits with regular expressions in java

我必須根據這些條件創建一個 java 程序來檢查密碼是否有效:

  • 至少 5 個字符長或最多 12 個字符長
  • 以大寫字母開頭
  • 以兩個不同的數字結尾
  • 至少包含以下一個特殊字符: ! " # $ % & ' ( ) * + -
  • 至少包含一個小寫字母

這是我到目前為止所寫的,我想知道檢查第二個條件的正則表達式是什么(密碼必須以 2 個不同的數字結尾)?

import java.util.Scanner;

public class PasswordValidation {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Please enter a password");
        
        String password = sc.next();

        if (isValid(password)) {
   
            System.out.println("OK");
        } else {
  
            System.out.println("NO");
        }
        
    }

        public static boolean isValid (String password) {
            return password.matches ("^[A-Z](?=.*[a-z])(?=.*[!#$%&'()+-]).{5,12}$");
        }
        

}

嘗試使用這個正則表達式模式:

^(?=.*[a-z])(?=.*[!"#$%&'()*+-])[A-Z].{2,9}(\d)(?!\1)\d$

Java代碼:

String password = "Apple$123";
if (password.matches("(?=.*[a-z])(?=.*[!\"#$%&'()*+-])[A-Z].{2,9}(\\d)(?!\\1)\\d")) {
    System.out.println("MATCH");
}

這將打印MATCH

以下是正則表達式模式的解釋:

^                         from the start of the password
    (?=.*[a-z])           assert that a lowercase letter be present
    (?=.*[!"#$%&'()*+-])  assert that a special character be present
    [A-Z]                 password starts with uppercase letter
    .{2,9}                followed by any 2 to 9 characters (total 5 to 12)
    (\d)                  2nd to last character is any digit
    (?!\1)\d              last character is any digit other than previous one
$                         end of the password

暫無
暫無

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

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