I have the following method to check allowed characters:
private boolean checkIfAllCharsAreValid(String test) {
boolean valid = false;
if (test.matches("^[a-zA-Z0-9,.;:-_'\\s]+$")) {
valid = true;
}
return valid;
}
but if test has the character - in it the match return false. Do i have to escape the -?
Inside
[…]the-symbol is treated specially. (You use it yourself in this special purpose in the beginning of your expression where you havea-z.)You need to escape the
-characteror put it last (or first) in the
[...]expression likeSome further notes:
Technically speaking all characters are valid in the empty string, so I would change from
+to*in your expression.String.matcheschecks the full string, so the^and$are redundant.Your entire method could be wirtten as