简体   繁体   中英

Invalid escape sequence \d

I'm trying to check if a password contain at least one lower case letter, one upper case letter, one digit and one special character.

i'm trying this:

if(!password.matches("(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])")){
        username = "Error";
    }

but give me an error saying: invalid escape sequence.

Someone can help me to solve the problem and can confirm that is a correct pattern?

Thanks, whit \\d don't do error but it don't match with a string like Paul%88 why?

Java will treat \ inside a string as starting an escape sequence . Make sure you use \\ instead (so that you get an actual \ character in the string) and you should be ok.

Quick Update : As Etienne points out, if you actually want a \ in the RegEx itself, you'll need to use \\\\ , since that will produce \\ in the string, which will produce \ in the RegEx.

New Question Update: You mention that your RegEx doesn't work, and I'm pretty sure that's because it's wrong. If you just want to ensure one of each type of character class is present, you may just want to create one RegEx for each class, and then check the password against each one. Passwords are pretty much guaranteed to be short (and you can actually control that yourself) so the perf hit should be minimal.

I used this to quickly test it: http://www.regexplanet.com/simple/index.html

Looks like it works if you put.* at the end. I guess you need to actually include a non-look-ahead regex as well.

Here is the entire regex:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*

Of course in your java code you must escape the backslash as mentioned already.

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