Andrew Andrew - 1 year ago 178
Java Question

Java Password Checker Pattern

The password checker program is supposed to take user input of a username and password and output whether the password is valid or invalid.

I've been trying to use regex for this but am having an issue. The pattern works for all my rules but one, the username rule.
Also, is there a way to change the output from "true" or "false" to something custom?

My code so far:

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(;

// 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-z])(?=.*[A-Z]).{8,}";
System.out.println(pw.matches(req)); // Can I customize the output?


I appreciate any help! :)

Answer Source

You should be able to just initially check if it has that sub-sequence. I would check that initially then check your password rules. So something like this (using a regex):

// get username and password
    System.out.println("Password can't have username in it...");
// make sure password follows rules...

Better would be to use the contains method on strings (docs).

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

As far as customizing the output of matches you can't. You'll need to conditionally branch and do something different.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download