Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid escape sequence \d

Tags:

java

regex

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?

like image 367
Matteo Avatar asked Jul 15 '11 14:07

Matteo


People also ask

Is \d an escape sequence?

Class-shorthand escapes (AREs only) provide shorthands for certain commonly-used character classes: \d. [[:digit:]]] Within bracket expressions, \d', \s', and \w' lose their outer brackets, and \D', \S', and \W' are illegal.

What is invalid escape sequence?

A string contains a literal character that is a reserved character in the Regex class (for example, the '(' or open parentheses character). Placing a '\' (backslash) in front of the character in the regular expression generates an 'Invalid escape sequence' compilation error.

What is the meaning of '\ n escape sequence?

For example, \n is an escape sequence that denotes a newline character.


1 Answers

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.

like image 178
dlev Avatar answered Sep 27 '22 16:09

dlev