java useDelimeter split on -

Viewed 73

I'm trying to parse a txt file that looks like

A - 19
B - 2
C - 3

and I am using the scanner method to read it in and split in the " - " so that my output will look like:

A
19
B
2
C
3

however it does not seem to be splitting correctly. This is what that part of the code looks like:

Scanner s = new Scanner(fileName).useDelimiter("\\s*-\\s*");
System.out.println(s.next());
System.out.println(s.next());

s.close();

I would expect this to look like:

A
19

but my output is:

A
19
B
2 Answers

You should use this regex for delimiter:

Scanner s = new Scanner(fileName).useDelimiter("\\s*-\\s*|\\R+");

Where \R+ matches 1 or more line breaks of any kind.

  public static void main(String[] args) throws FileNotFoundException {
    String fileName = "C://temp//split.txt";
    try (Scanner s = new Scanner(new File(fileName)).useDelimiter(" - ")) {
      while(s.hasNext()) {
        System.out.println(s.next());
      }
    }
  }
Related