【问题标题】:Java Password PatternJava 密码模式
【发布时间】:2017-02-02 14:11:24
【问题描述】:

密码检查程序应该接受用户输入的用户名和密码,并输出密码是否有效。

我一直在尝试为此使用正则表达式,但遇到了问题。该模式适用于我的所有规则,但用户名规则除外。 另外,有没有办法将输出从“true”或“false”更改为自定义?

到目前为止我的代码:

import java.util.regex.*;
import java.util.Scanner;

public class validPassword {
    private static Scanner scnr;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Variable Management
        String un, pw, req; // Variable Variable

        System.out.println("Please enter a username: ");
        // ^Need to implement so if it matches the password it's invalid^
          un = input.nextLine(); // Gathers user's username input
        System.out.println("Please enter a password: ");
          pw = input.nextLine(); // Gathers user's password input

        req = "(?=.*[0-9])(?=.*[a-zA-Z]).{8,}";
        System.out.println(pw.matches(req)); // Can I customize the output?
    }

}

感谢您的帮助! :)

【问题讨论】:

  • 您知道,在上次编辑中,您将含义从“必须包含数字、小写字母和大写字母”更改为“必须包含数字和小写大写字母” ?现在可以只使用小写和大写字母。是你不赞成我的回答吗?如果有,为什么?

标签: java regex passwords password-checker


【解决方案1】:

您应该能够最初检查它是否具有该子序列。 我会先检查一下,然后检查你的密码规则。 所以像这样(使用正则表达式):

// get username and password
if(pw.matches(".*"+Pattern.quote(un)+".*")){
    System.out.println("Password can't have username in it...");
}
// make sure password follows rules...

最好在字符串 (docs) 上使用 contains 方法。

if (pw.contains(un)) {...}

就自定义matches 的输出而言,您不能。你需要有条件地分支并做一些不同的事情。

【讨论】:

  • 我之前尝试了自己的 if 语句,但没有成功,我回头看了一下,发现有一些逻辑错误。
【解决方案2】:

对于用户名检查,您可以将正则表达式更改为

"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])((?<!" + Pattern.quote(un) + ").(?!" + Pattern.quote(un) + ")){8,}"

表示至少 8 个任意字符,且用户名前后均未出现。就像您在包含三个字符类的要求中使用正向前瞻一样,这是使用负向后视和负向前瞻。

关于自定义输出,只需使用三元表达式:

System.out.println(pw.matches(req) ? "yehaw" : "buuuuuh")

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2023-03-23
    • 1970-01-01
    • 2012-12-08
    • 2016-12-13
    相关资源
    最近更新 更多