为什么"hello \\ s*world"与"hello world"不匹配?

Nav*_*vin 9 java regex java.util.scanner

为什么此代码抛出InputMismatchException?

Scanner scanner = new Scanner("hello world");
System.out.println(scanner.next("hello\\s*world"));
Run Code Online (Sandbox Code Playgroud)

http://regexpal.com/中使用相同的正则表达式匹配(使用\ s代替\\ s)

Aff*_*ffe 11

与Matcher相反,Scanner内置了字符串的标记化,默认分隔符是空格.因此,在比赛开始之前,你的"hello world"会被标记为"hello""world".如果您在扫描到不在字符串中的内容之前更改了分隔符,那将是匹配,例如:

Scanner scanner = new Scanner("hello world");
scanner.useDelimiter(":");
System.out.println(scanner.next("hello\\s*world"));
Run Code Online (Sandbox Code Playgroud)

但它似乎真的适合你的情况,你应该只是使用一个Matcher.

这是"按预期"使用扫描仪的示例:

   Scanner scanner = new Scanner("hello,world,goodnight,moon");
   scanner.useDelimiter(",");
   while (scanner.hasNext()) {
     System.out.println(scanner.next("\\w*"));
   }
Run Code Online (Sandbox Code Playgroud)

输出将是

hello
world
goodnight
moon
Run Code Online (Sandbox Code Playgroud)