Search code examples
javacsvdelimiter

how to skip over whitespace while using a scanner with a delimitter?


I'm trying to read a list of comma separated values, I've needed to take a substring of these values as the entire file is not a csv. Because of my substring, and the line returns within the file, i need to be able to skip over the whitespace.

Ive tried putting both \n and \s in my delimiter and neither works. no matter what, line returns are not skippped. here is my code:

Scanner scan = new Scanner(fileContents);
        scan.useDelimiter("[\\s,]");
        while (scan.hasNextLine()) {
            System.out.println(scan.next());
        }
        System.out.println("done");

here are the results:

    
    161
    331.491712707182
    4
    1
    0
    75
    1
    0
    
    12089
    -100
    4  
    1
    0
    75
    0
    0
    

and my desired output:

    161
    331.491712707182
    4
    1
    0
    75
    1
    0 
    12089
    -100
    4  
    1
    0
    75
    0
    0

Solution

  • The problem appears to be caused by adjacent sections of whitespace. You can use (\s+|,) as your delimiter pattern instead, to treat any section of contiguous whitespace as a delimiter.

    You might even choose to use [\s,]+ to ensure that any adjacent delimiters are consumed together, if your input data is particularly messy.