密码在Java中,通过使用正则表达式的
问题描述:
我试图用正则表达式做一个密码,我不明白为什么我的代码不工作:密码在Java中,通过使用正则表达式的
import java.util.Scanner;
class test {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a password please.");
String password = scanner.nextLine();
int x;
String redex = "(^[0-9]+$)";
String redexx = "(^[A-Z]+$)";
boolean hasSpace = false;
boolean hasUpperCase = false;
boolean hasLetter = false;
boolean hasDigit = false; // we set four booleans to be able to bring up individual error messages.
if (password.length() > 8){
hasLetter = true;
} else {
System.out.println("Your password needs to be at least 8 characters long.");
if (password.matches(redexx)) { // we check to see if the password has at least an upper case letter, one or more digits and a space using regular expressions
hasUpperCase = true;
} if (password.matches(redexx)) {
hasDigit = true;
} if (password.indexOf(' ') == 1) {
hasSpace = true; }
} if (hasLetter && hasDigit && hasUpperCase && !hasSpace) {
System.out.println("Your password is strong.");
} if (!hasDigit) {
System.out.println("You need to put numbers in your password.");
} if (!hasUpperCase) {
System.out.println("You need to use an upper case letter in your password.");
} if (hasSpace) {
System.out.println("You need to delete any spaces in your password.");
} // if we use if statements (and not any "else" or "else if", we get to show all the possible error messages.
}
}
纠正“正则表达式”后“regexx”和编译后,当我输入一个完全适用的密码,它仍然会提示密码需要一个大写,它也需要一个数字
答
试试这个:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a password please.");
String password = scanner.nextLine();
boolean validLength = password.length() >= 8;
boolean hasLetter = password.matches(".*[a-zA-Z].*");
boolean hasDigit = password.matches(".*\\d.*");
boolean hasSpace = password.matches(".*\\s.*");
if (!validLength)
System.out.println("The password must be at least 8 characters long.");
else if (!hasLetter)
System.out.println("The password must contain at least one letter.");
else if (!hasDigit)
System.out.println("The password must contain at least one digit.");
else if (hasSpace)
System.out.println("The password must not contain spaces.");
else
System.out.println("Your password is strong.");
}
}
除了在你的问题的意见中提到的错误,你也可以使用正则表达式不正确。有关如何在Java中使用正则表达式的信息,请参阅Java regular expression constructs。
此外,空格字符实际上使密码更强,所以我建议允许用户输入空格字符。在我的答案的演示代码中,虽然用户不允许输入空格字符,因为这是您的要求。
答
问题可能是因为你没有把“正则表达式”用引号引起来。他们是字符串。
所以尝试:
String redex = "(^[0-9]+$)";
String redexx = "(^[A-Z]+$)";
你的意思是正则表达式? – procrastinator
你明白为什么这些行不能编译? String redex =(^ [0-9] + $); String redexx =(^ [A-Z] + $); – Stultuske
'password.length()> 8'表示密码必须至少有9个字符才能通过该测试,而不是8个,因为您之后写入3行。 –