gpt4 book ai didi

java - 通过使用正则表达式在 Java 中输入密码

转载 作者:行者123 更新时间:2023-12-02 12:10:46 24 4
gpt4 key购买 nike

我正在尝试使用正则表达式创建密码,但我不明白为什么我的代码不起作用:

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.
}
}

更正“regex”和“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 regular expression constructs有关如何在 Java 中使用正则表达式的信息。

此外,空格字符实际上使密码更强大,因此我建议允许用户输入空格字符。在我的答案的演示代码中,尽管用户不允许输入空格字符,因为这是您的请求。

关于java - 通过使用正则表达式在 Java 中输入密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com