Reputation: 171
I have
String b = "aasf/sdf/dfd/*";
Pattern.matches("[^ ]", b);
I keep getting returned false in Patter.matches();
Since it matches regex, all characters beside space character, shouldn't it return true?
Upvotes: 0
Views: 631
Reputation: 32797
Pattern.matches
would try to match the pattern exactly..
So it would return true
only if you have a single non space character as input.
Its like using \A[^ ]\z
where \A
is the beginning of input and \z
is end of input..
If you want to check for strings that doesn't contain space you can use
input.matches("[^ ]*");
Upvotes: 1
Reputation: 53525
As anirudh suggested, Pattern matchers are used differently (see the other answers for examples), I believe that what you were trying to do is the following:
String b = "aasf/sdf/dfd/*";
System.out.println("b.matches(\"[^ ]\") = " + b.matches("[^ ]"));
OUTPUT
b.matches("[^ ]") = false
Upvotes: 1
Reputation: 35405
Pattern.matches()
returns true
only if the entire string matches the regex. What you want to do is to see if the pattern occurs anywhere in the String
. You need to use Matcher.find()
for that.
e.g,
String testStr = "aasf/sdf/dfd/*";
Pattern patt = Pattern.compile("[^ ]");
Matcher m = patt.matcher(testStr);
while (m.find()) {
System.out.println(m.group(0));
}
This will print all matches. If you just need to know if a pattern is found, just check if m.find()
is true
.
Upvotes: 0
Reputation: 5147
No, coz you try to match whole string to NON-SPACE character.
String b = "aasf/sdf/dfd/*";
Pattern.matches("[^ ]*", b);
This one will return true
Upvotes: 1