简体   繁体   中英

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM