用户将以下内容输入到扫描仪中:
"a " (character 'a' followed by a single space)
我明白为什么这有效:
Scanner in = new Scanner(System.in);
System.out.println(in.nextLine().matches("a\\s"));
但我不明白为什么这不起作用:
Scanner in = new Scanner(System.in);
System.out.println(in.next().matches("a\\s"));
第一个代码块(顶部的代码块)返回 true
,而第二个代码块(底部的代码块)返回 false
两者之间的唯一区别是,一个使用 nextLine()
,另一个使用 next()
谁能解释一下这种行为?我知道最佳实践取决于用户 Pattern 和 Matcher 类,但这确实困扰着我。
我也尝试过("a(\\s)")
但不幸的是这给了我相同的结果。我记得读过 .matches()
方法在输入的开头附加一个 ^
并在末尾附加一个 $
,但这应该仍然没有让它返回 false,我已经尝试过,它确实返回了 false。
最佳答案
当您使用next()
方法时,它只会扫描文件的一个字符。因此 in.next()
将返回 a
、 \
、 \
,然后返回 s
.通过使用nextLine()
,您将扫描整行,从而扫描a\\s
。希望这有帮助!
关于java - Java String .matches() 的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49933658/