Using Java Scanner's hasNext(Pattern) to find a leading '+'
I have a scanner that has been working smoothly up until I try the hasNext(Pattern) method to look for a leading '+' character. Here's what I have been trying to do:
File file = new File("Somefile.txt");
Scanner input = new Scanner(file);
whil开发者_如何学运维e (!input.hasNext(Pattern.compile("^\\+"))) {
System.out.println("No leading +:" + input.next());
}
Which sure seems to make sense. However the program loops endlessly past plenty of lines with leading '+'. What am I doing wrong?
The problem is that you're trying to match tokens against beginning-of-line with ^
. The tokens will never contain new-lines to begin with (they will simply be the substrings that are separated by the delimiter), so ^
doesn't make sense. If you want to read lines with the scanner, I suggest you do
Scanner input = new Scanner(file).useDelimiter("\n");
Then simply drop the ^
and it will work:
while (!input.hasNext(Pattern.compile("\\+.*")))
System.out.println("No leading +: " + input.next());
The javadoc says of the hasNext() method:
Returns true if the next complete token matches the specified pattern.
A "complete token" in your case, since you haven't changed the delimiter, is bounded by whitespace. You will find only isolated "+" signs, not "+" signs at the beginning of tokens.
Also, it's not clear what you mean by "leading '+' character". Do you mean at the beginning of a line or at the beginning of each token?
精彩评论