Reputation: 5180
I have a string of "abc123("
and want to check if contains one or more chars that are not a number or character.
"abc123(".matches("[^a-zA-Z0-9]+");
should return true in this case? But it dose not! Whats wrong?
My test script:
public class NewClass {
public static void main(String[] args) {
if ("abc123(".matches("[^a-zA-Z0-9]+")) {
System.out.println("true");
}
}
}
Upvotes: 0
Views: 242
Reputation: 66156
Expression [^A-Za-z0-9]+
means 'not letters or digits'. You probably want to replace it with ^[A-Za-z0-9]+$
which means 'Only letters or digits'.
Upvotes: 2
Reputation: 17321
In Java, the expressions has to match the entire string, not just part of it.
myString.matches("regex") returns true or false depending whether the string can be matched entirely by the regular expression. It is important to remember that String.matches() only returns true if the entire string can be matched. In other words: "regex" is applied as if you had written "^regex$" with start and end of string anchors. Source
Your expression is looking for part of the string, not the whole thing. You can change your expression to .*YOUR_EXPRESSION.*
and it will expand to match the entire string.
Upvotes: 5
Reputation: 725
Rather than checking to see if it contains only letters and numbers, why not check to see if it contains anything other than that? You can use the not word group (\W) and if that returns true than you know the string contains something other than the characters you are looking for,
"abc123(".matches("[\W]");
If this returns true than there is something other than just word characters and digits.
Upvotes: 4