18

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.

Ripon Al Wasim
  • 34,088
  • 37
  • 146
  • 165
tomejuan
  • 181
  • 1
  • 1
  • 3

6 Answers6

23
 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
jmj
  • 225,392
  • 41
  • 383
  • 426
7

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

Andrew White
  • 50,300
  • 17
  • 108
  • 132
  • 4
    It escapes the second \. Regex use \n to mean newline but so does Java so you write \\n which gets translated to \n for the regex. – Andrew White Feb 04 '11 at 14:35
  • Wonder why tomejuan didn't respond. Maybe "escapes", "regex", or the explanation about the second '\'. – DSlomer64 Jan 03 '18 at 01:39
2

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")
Jeremy Caney
  • 4,585
  • 13
  • 32
  • 54
1

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

adrianboimvaser
  • 2,594
  • 1
  • 20
  • 30
0

Jigar is absolutely correct. But if it doesn't work, try ",|\\r"

since most text files have \r\n instead of just \n

Orange
  • 1
0

Using Scan Delimiters for Excel files - don't overlook the RegEx thing. In my case the excel file is delimitedby '|'. I have been spending significant time to parse rows using scanner.useDelimiter("|"), and got back character by character. Replacing that with scanner.useDelimiter("\\|") has solved my issue!

Gil Shapir
  • 79
  • 1
  • 7