开发者

Multiple delimiters in Scanner class of Java

开发者 https://www.devze.com 2023-02-09 02:28 出处:网络
How do I use the useDelimiter() method of the Scanner class to use both the comma (,) and the new line chara开发者_JS百科cter (\\n) as delimiters?

How do I use the useDelimiter() method of the Scanner class to use both the comma (,) and the new line chara开发者_JS百科cter (\n) as delimiters?

I am parsing some text from a csv file.


 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
  • JavaDoc


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


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


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")


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

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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消