【发布时间】:2020-12-14 11:48:10
【问题描述】:
这是我的解析方法。
public void loadInput(File fileName) throws IOException {
try {
Scanner s = new Scanner(fileName);
int numWords = 0;
while (s.hasNext("(?<!')[\\w']+")) {
System.out.println("word:" + s.next());
numWords++;
}
System.out.println("Number of words: " + numWords);
} catch (IOException e) {
System.out.println("Error accessing input file!");
}
}
这是一个示例输入文件:
Alice was beginning to get very tired of sitting by her sister
on the bank, and of having nothing to do: once or twice she had
peeped into the book her sister was reading, but it had no
pictures or conversations in it, `and what is the use of a book,'
thought Alice `without pictures or conversation?'
So she was considering in her own mind (as well as she could,
for the hot day made her feel very sleepy and stupid), whether
the pleasure of making a daisy-chain would be worth the trouble
of getting up and picking the daisies, when suddenly a White
Rabbit with pink eyes ran close by her.
它只匹配这些词:
word:Alice
word:was
word:beginning
word:to
word:get
word:very
word:tired
word:of
word:sitting
word:by
word:her
word:sister
word:on
word:the
Number of words: 14
不知何故,扫描仪认为它已到达文件末尾,这是不正确的。关于为什么会发生这种情况的任何想法?我检查了我的正则表达式,它似乎确实有效(一个单词包含字母 a-z 和撇号)。谢谢!
【问题讨论】:
-
请注意,您的解析器未解析的第一个单词
bank也是文本的第一个单词,其后跟一个不是字母或空格的字符(在这种情况下是逗号)
标签: java regex java.util.scanner