Actually, this is the one that causes the problem, trying to use a new line at the end of the last line .: - / This is absolutely true for the last line to end abruptly without a newline, but your regular expression requires it to be one. You may be able to fix this by replacing the new line with an anchor or look, but there are much simpler ways to do this.
One of them is to override the default separator and iterate over the fields with next() :
Scanner sc1 = new Scanner("abcd;\nxyz"); sc1.useDelimiter("[;\r\n]+"); while (sc1.hasNext()) { System.out.printf("%s%n", sc1.next()); }
Another is to nextLine() through the lines using nextLine() (using the default delimiter), and then split each line into a semicolon:
Scanner sc2 = new Scanner("abcd;\nxyz"); while (sc2.hasNextLine()) for (String item : sc2.nextLine().split(";")) { System.out.printf("%s%n", item); }
The scanner API is one of the most hyped and unintuitive I've ever worked with, but you can significantly reduce the pain of using it if you remember these two important points:
- Think in terms of matching separators rather than fields (e.g. for String
split() ). - Never call one of the
nextXXX() methods without first calling the corresponding hasNextXXX() method.
source share