这是我当前的代码:
import java.util.*;
import java.util.regex.*;
public class TestClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
if (password.length() >= 10) {
if (Pattern.matches("[a-zA-Z]\\d{2}", password)) {
System.out.println("Password is valid");
}
}
}
}
描述
密码规则:
这是我一直在尝试用于验证密码的代码,但是它不会打印我的输出。
我将使用以下正则表达式模式来声明您的要求:
^(?!.*[^A-Za-z0-9])(?=.{10,}).*\\d.*\\d.*$
此模式表明:
^ from the start of the password
(?!.*[^A-Za-z0-9]) look ahead and assert that we do NOT see any non letters or digits
(?=.{10,}) look ahead and assert that password length be 10 or longer
.*\\d.*\\d.* then match any pattern so long as two digits be present
$ end of the password
我可能只是直接String#matches
在这里使用:
Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
if (password.matches("(?!.*[^A-Za-z0-9])(?=.{10,}).*\\d.*\\d.*")) {
System.out.println("Password is valid");
}
请注意,将其用于时,我们将从regex模式中删除^
和$
锚,String#matches
因为此方法将模式隐式地应用于整个字符串输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句