Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy split without final trim

Tags:

groovy

I'm parsing a CVS file like the following:

"07555555555",25.70,18/11/2010,01/03/2011,N,133,0,36,,896,537,547,,Mr,John,Doe,,
"07555555555",10.15,26/01/2011,01/03/2011,N,16,0,100,,896,537,547,,Mrs,Jane,Doe,,[email protected]

The thing is that when using a script like this:

file.eachLine{ line ->

    items = line.split(",")
    println items.length
}

The result is like the following:

16
18

Which makes me thing that the split function removes a final values. I need it to have all the items even if they are empty. Any idea?

like image 683
Sergi Sorribas Avatar asked Mar 09 '11 12:03

Sergi Sorribas


1 Answers

I think you want to do:

items = line.split(',', -1)

to make sure you get all the tokens

(according to the javadoc):

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

like image 57
tim_yates Avatar answered Nov 15 '22 09:11

tim_yates