Aramza
Aramza

Reputation: 193

Java Password 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(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?
    }

}

I appreciate any help! :)

Upvotes: 0

Views: 1279

Answers (2)

Vampire
Vampire

Reputation: 38669

For the username check you can change the regex to

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

which means at least 8 arbitrary characters that are not followed or preceded by the username. This is with negative lookbehind and negative lookahead just as you used the positive lookahead for the requirement that the three characterclasses are contained.

And regarding the custom output, just use a ternary expression:

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

Upvotes: 0

Neil Locketz
Neil Locketz

Reputation: 4318

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
if(pw.matches(".*"+Pattern.quote(un)+".*")){
    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.

Upvotes: 1

Related Questions