为什么这段代码会抛出一个InputMismatchException?
Scanner scanner = new Scanner("hello world");
System.out.println(scanner.next("hello\\s*world"));相同的正则表达式在http://regexpal.com/中匹配(使用\s而不是\s)
发布于 2011-06-11 01:16:47
与Matcher相反,Scanner内置了字符串的标记化,默认分隔符是空格。因此,在比赛开始之前,您的"hello world“将被标记为"hello”"world“。如果在扫描之前将分隔符更改为不在字符串中的内容,则会匹配,例如:
Scanner scanner = new Scanner("hello world");
scanner.useDelimiter(":");
System.out.println(scanner.next("hello\\s*world"));但对于您的情况,似乎真的应该只使用Matcher。
这是一个“按预期”使用扫描仪的示例:
Scanner scanner = new Scanner("hello,world,goodnight,moon");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next("\\w*"));
}输出将是
hello
world
goodnight
moon发布于 2011-06-11 01:25:14
扫描器的默认分隔符是空格,因此扫描器可以看到两个元素hello和world。并且hello\s+world与hello不匹配,因此抛出NoSuchElement异常。
发布于 2011-06-11 01:27:18
这些输入是有效的:
"C:\Program Files\Java\jdk1.6.0_21\bin\java" RegexTest hello\s+world "hello world"
'hello world' does match 'hello\s+world'代码如下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
if (args.length > 0) {
Pattern pattern = Pattern.compile(args[0]);
for (int i = 1; i < args.length; ++i) {
Matcher matcher = pattern.matcher(args[i]);
System.out.println("'" + args[i] + "' does " + (matcher.matches() ? "" : "not ") + "match '" + args[0] +"'");
}
}
}
}https://stackoverflow.com/questions/6309776
复制相似问题