检查字符串是否以两个不同的数字结尾,并在java中使用正则表达式

thigvfpy  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(319)

我必须创建一个java程序,根据以下条件检查密码是否有效:
长度至少5个字符或最多12个字符
以大写字母开头
以两个不同的数字结尾
至少包含以下一个特殊字符:!“#$%&'()*+-
包含至少一个小写字母
这是我到目前为止写的,我想知道检查第二个条件(密码必须以两个不同的数字结尾)的正则表达式是什么?

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}$");
        }

}

rkue9o1l

rkue9o1l1#

尝试使用此正则表达式模式:

^(?=.*[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

相关问题