Reputation: 56934
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!
Upvotes: 0
Views: 2306
Reputation: 32807
The regex should be ^.*[~@+%|].*$
Alternatively you can use [~@+%|]
with find
method instead of matches
Upvotes: 5
Reputation: 5103
If you are looking a clear and concise way to do it I wouldn't use regexp, as it's API in Java tends to get messy. Apache commons-lang
has StringUtils.containsAny("text","blacklisted");
. It's usually a good library to include anyways as it complements Java with much more than couple of string utilities.
Upvotes: 1