java正则表达式函数中的问题.它未进行验证.帮帮我


// I'm trying to validate my password but returns false and i am not able to find my error in it.
// i have tried alot but not finding whats wrong in it.        
public class main {
public static void main(String[] args) {
while (true) {
System.out.println("Enter your password");
String mpassword = sc.next();
boolean flag = Utilities.validatePassword(mpassword); //calling method 
//from here
if (!flag) {
System.out.println("NOT VALID");
}
else {
System.out.println("PERFECT");
break;
}
pro.setPassword(mpassword);
}
}
//here is my regex validation 
public class utilities {
public static boolean validatePassword(String password) {
String pattern = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,})";
if (pattern.matches(password)) {
System.out.println("matched");
return true;
}
return false;
}
}
String pattern = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,})";
if (pattern.matches(password)) { ... }

这不是匹配模式的方式。您需要使用Pattern类。

String password = "harshal1A@";
String pattern = "((?=.*[a-z])(?=.*\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,})";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(password);
System.out.println(m.matches());

或者,正如@Andreas所指出的,你只需要撤销通话。

password.matches(pattern)

在正则表达式中,使用\\转义d两次。您只需要使用\对其进行一次转义。

最新更新