简体   繁体   English

Java String .matches()的奇怪输出

[英]Weird output with Java String .matches()

User inputs the following into scanner: 用户将以下内容输入扫描仪:

"a " (character 'a' followed by a single space) “ a”(字符“ a”后跟一个空格)

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 第一个代码块(顶部的代码)返回true而第二个代码块(底部)返回false

The only difference between the two is one is using nextLine() and the other next() 两者之间的唯一区别是一个是使用nextLine()而另一个是next()

Can anyone explain this behavior? 谁能解释这种行为? I know best practices dictates to user Pattern and Matcher class but this is really bothering me. 我知道最佳实践决定了用户Pattern和Matcher类,但这确实让我感到困扰。

I've also tried ("a(\\\\s)") but this unfortunately gave me the same results. 我也尝试过("a(\\\\s)")但是不幸的是,它给了我相同的结果。 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. 我记得读过.matches()方法在输入的开头附加了一个^ ,并在末尾附加了一个$ ,但这仍然不应该使它返回false,我已经尝试过了,但是确实返回了false。

When you use the method next() it will only scan for one character of the file. 当您使用next()方法时,它将仅扫描文件的一个字符。 Therefore in.next() would return a , \\ , \\ , and then s . 因此in.next()将返回a\\\\s By using nextLine() you are scanning the entire line and thus a\\\\s . 通过使用nextLine()您将扫描整行,从而扫描a\\\\s Hope this helped! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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