I am using regular expressions in Java to check the input of a password field. The following is the code for checking the password:
final Pattern check = Pattern.compile( "^[a-z0-9A-Z!$%*()-_[]{};:@#<>,./?\\|]+$");
if (!check.matcher(password).matches()) {
errors.put("password", "Invalid input");
}
When i submit an input containing symbols, for example %, the following exception is being generated:
exception
java.util.regex.PatternSyntaxException: Unclosed character class near
index 37 ^[a-z0-9A-Z!$%*()-_[]{};:@#<>,./?\|]+$
^
I’ve already used other regex expressions in this same code and they work fine… Only this part is giving me trouble.
Does any of you maybe know the cause for this error?
Thanks for your help in advance!
Your character class has two problems:
]in it,-placement makes it ambiguous.What’s more, Java also requires that you escape the
[(other regex engines won’t require that):You should write it a such: