简体   繁体   中英

regular expression java password

Hey I have searched through stackoverflow and can't seem to find an answer. I need to check if the typed password only contains letters and numbers.

here's the code

System.out.println("Type the Password for the new user: ");
    String password = input.nextLine();

    if (!password.matches("[^A-Za-z0-9]")) {            
         System.out.println("The password must only contain letters and/or numbers");
            showAddUser();
    }else{

             System.out.println("The password is valid");

What am I doing wrong ? Help appreciated :)

Try this:

if (!password.matches("^([A-Za-z0-9]+)$")) {   

What a shame - this regular expression excludes "correct horse battery staple".

http://xkcd.com/936/

With String.matches("[A-Za-z0-9]") you're actually matching whether the String contains of exactly one alphanumeric. You probably want it to be repeated. You could try String.matches("[A-Za-z0-9]+") to match at least one alphanumeric, not exactly one.

By the way, I wouldn't trust a system which doesn't allow me to use punctuation as well.

删除否定项:

if (password.matches("[^A-Za-z0-9]")) { 

尝试if (!password.matches("[^A-Za-z0-9]+"))

You can use VT password library for password validation. You can use AllowedCharacterRule or RegexRule for this. With this tool you can easily add more rules if needed later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM