The regular expression to validate just the mentioned set of characters may be simplified and used with String::matches
:
// return true if expression contains only valid characters, false otherwise
private static boolean hasValidChars(String expr) {
return expr.matches("[-+*/0-9\\s(){}\\[\\]]*");
}
For the given set of characters, only square brackets [
, ]
need to be escaped while used inside character range, -
should not be escaped being the first character in the range.
If the regular expression should return true
if invalid character is detected, existing expression should be negated:
private static boolean hasInvalidChars(String expr) {
return expr.matches("(?![-+*/0-9\\s(){}\\[\\]]*$).*");
}
or the character set could be negated [^...]
(.*
need to be supplied to look for any invalid character in the expression, as matches
checks the entire string.)
private static boolean hasInvalidChars(String expr) {
return expr.matches(".*([^-+*/\\s0-9(){}\\[\\]]).*");
}
Tests:
for (String expr : Arrays.asList("(123 + 456) - 789", "abc + 322", "(33 / [11 - x])")) {
System.out.println(expr);
System.out.println("invalid? " + hasInvalidChars(expr));
System.out.println("valid? " + hasValidChars(expr));
System.out.println("---");
}
Output:
(123 + 456) - 789
invalid? false
valid? true
---
abc + 322
invalid? true
valid? false
---
(33 / [11 - x])
invalid? true
valid? false
---