gpt4 book ai didi

java - Java.util.Scanner next(Pattern) 方法的问题/混淆

转载 作者:行者123 更新时间:2023-11-29 07:22:58 25 4
gpt4 key购买 nike

我构建了一个正则表达式,我将其编译为一个模式来查找 Fortran Real*8 数字。棘手的一点是我正在读取的文件是一行有几百万列的文件..当我这样做时:

Scanner recordScanner = new Scanner(recordString);
String foundReal = recordScanner.findInLine(real8Regex);

我得到了我要找的东西,但是当我使用 next(Pattern) 方法时,我得到了一个 InputMismatchException。奇怪的是,考虑到 findInLine 和 next 返回字符串。

Scanner recordScanner = new Scanner(recordString);
String foundReal = recordScanner.next(real8Regex);

在使用 next() 方法时我是否遗漏了一些关键的东西?

最佳答案

是否是“并非所有标记都匹配模式,因此 next(Pattern) 卡在第一个不匹配的标记处”的问题?

next(Pattern) 可以这样使用:

String toSearch = "ab123d4e::g67f912g34h";
Scanner aScanner = new Scanner(toSearch);
aScanner.useDelimiter("[a-z]+");
while (aScanner.hasNext("[0-9]+"))
{
System.out.println(aScanner.next("[0-9]+"));
}

但只会输出 123 和 4,因为不匹配的第三个标记会导致 while 循环终止。然而,在那种情况下,我应该只使用 hasNext()next()

我正在努力想出使用 next(Pattern) 的真正原因,因为它会卡在第一个与模式不匹配的标记处。 next(Pattern) 不是 意思是“返回匹配 Pattern 的当前位置之后的第一个标记”;它的意思是“如果匹配模式,则返回序列中的下一个标记;否则什么都不做”

您(大概)需要读取所有标记,因此最好使用 hasNext()next() 然后使用 Matcher 针对每个 token 所需的 Pattern

最后,你可能会找到question 842496有用

关于java - Java.util.Scanner next(Pattern) 方法的问题/混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1285259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com