I want to write a simple validator to throw an exception if a String contains “illegal characters”, specifically:
~, @, +, % and |
I’m searching for the cleanest way of doing this, and was hoping that there was a way to define a “blacklist” regex that might look something like:
String blacklist = "~@+%|";
String toValidate = getInputFromUser();
if(toValidate.matches(blacklist))
throw new RuntimeException("Illegal characters found!");
However I know that the regex is incorrect. Am I heading in the right direction or am I way off base (i.e. is there a much simpler solution)? Thanks in advance!
The regex should be
^.*[~@+%|].*$Alternatively you can use
[~@+%|]withfindmethod instead ofmatches