Groovy split csv and empty fields

Groovy split seems to ignore empty fields.

Here is the code:

line = abc,abc,,, line.split(/,/) println 

prints only ..

 abc abc 

Empty fields seem to be ignored. How to get empty fields using split?

+4
source share
2 answers

First of all, the split (regex) method is not provided by Groovy, it is provided by Java.

Secondly, you can achieve what you need using a common split (regex, int limit) , as shown below:

 def line = "abc,abc,,," println line.split(/,/, -1) //prints [abc, abc, , , ] println line.split(/,/, -1).size() //prints 5 

Note: - The String Array page that you get in print will generate a compilation error when it is approved. But you can use the result as a regular list.

 line.split(/,/, -1).each{println "Hello $it"} 

I would prefer to use limit 0 or an overloaded split to remove unnecessary blank lines.

Explanation when using -1 as the limit:
Click on the descriptions below from 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 the largest n - 1 time, the length of the array will be no more than n, and the last element of the array will contain all the input data for the last matched separator. If n is not positive, then the template will be applied as many times more, 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 the final empty lines will be discarded.

+9
source

Interesting. The split method works as expected if there is a non-empty element at the end.

 def list = 'abc,abc,,,abc'.split(/,/) println list // prints [abc, abc, , ] assert list.size() == 5 assert list[0] == 'abc' assert list[1] == 'abc' assert list[2] == '' assert list[3] == '' assert list[4] == 'abc' 

Perhaps you could just add a dummy character to the end of the line and raise the result:

 def list = 'abc,abc,,,X'.split(/,/) - 'X' println list // prints [abc, abc, , ] 
+2
source

Source: https://habr.com/ru/post/1491033/


All Articles