Multiple delimiters in Scanner class of Java

廉价感情. 提交于 2020-01-09 07:54:10

问题


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.


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



回答2:


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




回答3:


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




回答4:


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

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




回答5:


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!



来源:https://stackoverflow.com/questions/4898263/multiple-delimiters-in-scanner-class-of-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!