I’m testing if a string is valid/invalid by checking if certain characters exists. Strings that contain ; # / % = | + \ ” < > are deemed invalid. I’ve the following implementation in Java currently, but I’d prefer a more elegant regex solution.
public boolean isStringValid(String name) {
if ( name.contains(";")
|| name.contains("#")
|| name.contains("/")
|| name.contains("%")
|| name.contains("=")
|| name.contains("|")
|| name.contains("+")
|| name.contains("\\")
|| name.contains("\"")
|| name.contains("<")
|| name.contains(">")) {
return false;
}
else {
return true;
}
}
What I’ve done is changed it to the following,
public boolean isNameValid(String name) {
return !Pattern.matches(".*(;|#|/|%|=|\\||\\+|\\\\|\"|<|>)+.*", name);
}
but I can’t seem to get the regex string right. The original regex string before adding in all the Java escape characters is as follows,
.*(;|#|/|%|=|\||\+|\\|"|<|>)+.*
Using character classes like [A-z] doesn’t seem to be an option because a name like “d@vik” is supposed to be considered valid in my case.
You are almost right. Just use
find()method instead ofmatches(). And compile pattern only once. This is the most expensive operation. And you can simplify you pattern using[]: in this case you do not have to write|between subpatterns you are looking for:Now re-write you
isNameValid()as following:BTW pay attention on backslash. If you want your pattern to include backslash it should be written 4 times: twice for regex escaping and twice for java escaping.