Multiple delimiters in Scanner class of Java

前端 未结 6 1367
深忆病人
深忆病人 2020-12-03 17:04

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

相关标签:
6条回答
  • 2020-12-03 17:44

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

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

    0 讨论(0)
  • 2020-12-03 17:48

    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 讨论(0)
  • 2020-12-03 17:52
     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
    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2020-12-03 18:02

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

    0 讨论(0)
  • 2020-12-03 18:03

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

    0 讨论(0)
提交回复
热议问题