I have the following characters that I would like to be considered “illegal”:
~, #, @, *, +, %, {, }, <, >, [, ], |, “, ”, \, _, ^
I’d like to write a method that inspects a string and determines (true/false) if that string contains these illegals:
public boolean containsIllegals(String toExamine) {
return toExamine.matches("^.*[~#@*+%{}<>[]|\"\\_^].*$");
}
However, a simple matches(...) check isn’t feasible for this. I need the method to scan every character in the string and make sure it’s not one of these characters. Of course, I could do something horrible like:
public boolean containsIllegals(String toExamine) {
for(int i = 0; i < toExamine.length(); i++) {
char c = toExamine.charAt(i);
if(c == '~')
return true;
else if(c == '#')
return true;
// etc...
}
}
Is there a more elegant/efficient way of accomplishing this?
You can make use of
PatternandMatcherclass here. You can put all the filtered character in a character class, and useMatcher#find()method to check whether your pattern is available in string or not.You can do it like this: –
find()method will return true, if the given pattern is found in the string, even once.Another way that has not yet been pointed out is using
String#split(regex). We can split the string on the given pattern, and check the length of the array. If length is1, then the pattern was not in the string.If
arr.length > 1, that means the string contained one of the character in the pattern, that is why it was splitted. I have passedlimit = 2as second parameter tosplit, because we are ok with just single split.