19

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
  • 36,924
  • 42
  • 155
  • 176
tomejuan
  • 191
  • 1
  • 1
  • 3

6 Answers6

27
 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
  • 237,923
  • 42
  • 401
  • 438
8

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

Andrew White
  • 52,720
  • 19
  • 113
  • 137
  • 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

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

adrianboimvaser
  • 2,651
  • 1
  • 22
  • 30
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
  • 7,102
  • 69
  • 48
  • 77
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
  • 119
  • 1
  • 7