java - 在java中使用正则表达式检查字符串是否以2个不同的数字结尾
问题描述
我必须创建一个 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
推荐阅读
- apache-camel - 根据标题动态加载骆驼的身体
- c++ - Sqlite3 数据库文件可删除仍可访问
- java - 试图在我的代码中找到数据库连接泄漏,使用 Spring / JPA / Hikari
- c# - 如何在 WPF Gridview 中获取检查的行值
- javascript - 数据表服务器端处理中的 Ajax 错误
- c++ - 在命名成员函数重载解析期间,“this”何时不在范围内?
- jquery - 当我单独使用代码以及将它与我的代码一起使用时出现问题
- makefile - 递归运行make后更新时间戳
- javascript - Ajax 的 Onreadystatechange Return Uncaught Typeerror
- azure - Google Doc 查看器未加载 Azure 共享访问签名 (SAS) 文件