【发布时间】:2016-09-30 17:34:29
【问题描述】:
我正在读取一个具有这种模式的文件:(section1, section2, section3) ... 但不能保证格式,这意味着我必须处理像一个部分在单独的行中,许多部分在一行中这样的情况。而且我还需要存储每个令牌的偏移量。所以我正在运行这样的代码,使用 Matcher 因为它提供了偏移量和标记:
`define a global matcher
while() {
readSection1(matcher, other parameters);
readSection2(matcher, other parameters);
readSection3(matcher, other parameters);
}
你可以看到我正在尝试通过这个匹配器,以便我可以从我停止的地方开始。但现在我有一个问题。在我上次的 readSection3 方法结束后,我测试了我的 matcher 没有结束,所以我开始了新一轮的阅读。 但是,当我再次进入 while 循环并将匹配器传递给我的 readSection1 方法时,匹配器突然结束了!为什么会这样?
我还做了一个小测试:
String loop = "a b c d e f g h i j k l";
Matcher loopMatcher = Pattern.compile("\\S+").matcher(loop);
boolean loopEnded = false;
while (!loopEnded) {
use(loopMatcher);
if (loopMatcher.hitEnd()) {
loopEnded = true;
}
}
public static void use(Matcher matcher) {
if (!matcher.find()) {
System.out.println("loop not ended but matcher hit end");
}
}
它也会打印错误消息。为什么?!
好的,奇怪的事情发生了,现在我再次运行这个小程序,错误消失了,但它仍然在我的大程序中。
【问题讨论】:
标签: java while-loop matcher