Multiple delimiters in Scanner class of Java

67,253

Solution 1

 Scanner s = new Scanner("hello, world \n hello world");
 s.useDelimiter(",|\\n");
 while(s.hasNext()){
          System.out.println(s.next());

 }

Output

hello
 world 
 hello world

Solution 2

How about useDelimiter(",|\\n");

Solution 3

useDelimiter takes a regex pattern, so, it would be something like ",|\n"

Solution 4

My text file has entries like:

01-jan-2020,102
02-jan-2020,103
…

To read the two values from each row, it worked with the following, since each line end was having both \r and \n characters:

Scanner.useDelimiter(",|\\r\\n")
Share:
67,253
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    How do I use the useDelimiter() method of the Scanner class to use both the comma (,) and the new line character (\n) as delimiters?

    I am parsing some text from a csv file.