Reputation: 337
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.
Upvotes: 1
Views: 5146
Reputation: 115328
You are almost right. Just use find()
method instead of matches()
. 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:
private static Pattern validator = Pattern.compile("[;%#=\\+]"); // etc: write all characters you need.
Now re-write you isNameValid()
as following:
public boolean isNameValid(String name) {
return !validator.find();
}
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.
Upvotes: 1
Reputation: 354506
You can negate character classes:
Pattern.matches("[^;#/%=|+\\\\\"<>]+", name);
Upvotes: 1