[英]Check if string ends with 2 different digits with regular expressions in java
I must create a java program to check if the password is valid or not based on these conditions:我必须根据这些条件创建一个 java 程序来检查密码是否有效:
This is what I have written so far, and I want to know what's the regular expression to check the second condition (that the password must end with 2 different digits)?这是我到目前为止所写的,我想知道检查第二个条件的正则表达式是什么(密码必须以 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}$");
}
} }
Try using this regex pattern:尝试使用这个正则表达式模式:
^(?=.*[a-z])(?=.*[!"#$%&'()*+-])[A-Z].{2,9}(\d)(?!\1)\d$
Java code: Java代码:
String password = "Apple$123";
if (password.matches("(?=.*[a-z])(?=.*[!\"#$%&'()*+-])[A-Z].{2,9}(\\d)(?!\\1)\\d")) {
System.out.println("MATCH");
}
This prints MATCH
.这将打印
MATCH
。
Here is an explanation of the regex pattern:以下是正则表达式模式的解释:
^ 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.