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 have a-z
.)
You need to escape the -
character
[a-zA-Z0-9,.;:\-_'\s]
^
or put it last (or first) in the [...]
expression like
[a-zA-Z0-9,.;:_'\s-]
^
Some further notes:
Technically speaking all characters are valid in the empty string, so I would change from +
to *
in your expression.
String.matches
checks the full string, so the ^
and $
are redundant.
Your entire method could be wirtten as
return test.matches("[a-zA-Z0-9,.;:_'\\s-]*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With