Aren Tahmasian
Aren Tahmasian

Reputation: 43

Weird output with Java String .matches()

User inputs the following into scanner:

"a " (character 'a' followed by a single space)

I understand why this works:

Scanner in = new Scanner(System.in);
System.out.println(in.nextLine().matches("a\\s"));

But I don't understand why this doesn't work:

Scanner in = new Scanner(System.in);
System.out.println(in.next().matches("a\\s"));

The first block of code (the one on top) returns true while the second one (bottom) returns false

The only difference between the two is one is using nextLine() and the other next()

Can anyone explain this behavior? I know best practices dictates to user Pattern and Matcher class but this is really bothering me.

I've also tried ("a(\\s)")but this unfortunately gave me the same results. And I recall reading that .matches() method appends a ^ at the beginning of the input and a $ at the end, but this should still not make it return false and I have tried it out and it did return false.

Upvotes: 0

Views: 78

Answers (1)

Rohun Agrawal
Rohun Agrawal

Reputation: 54

When you use the method next() it will only scan for one character of the file. Therefore in.next() would return a , \ , \ , and then s . By using nextLine() you are scanning the entire line and thus a\\s. Hope this helped!

Upvotes: 1

Related Questions