Groovy分割csv和空字段 [英] Groovy split csv and empty fields

查看:125
本文介绍了Groovy分割csv和空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy split似乎忽略了空字段。



这是代码:

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

仅打印..

  abc abc 

它似乎忽略空字段。首先,方法

Groovy不提供oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29rel =noreferrer> split(正则表达式),它是由Java提供的。

第二,你可以通过使用通用的 split(正则表达式,整数限制)如下:

  def line =abc,abc ,,,

println line.split(/,/, - 1)//打印[abc,abc,,]
println line.split(/,/,-1).size()//打印5

注意: -

在打印时,最终会出现的字符串数组会导致编译错误。但是,您可以将结果用作普通列表。

  line.split(/,/,-1).each {printlnHello $ it} 

我宁愿使用限制0或重载的分割来放弃不需要的空字符串。



使用-1作为限制的解释:

强调javadoc中的以下语句。


limit参数控制模式应用
的次数,因此影响结果数组的长度。如果
的limit n大于零,那么该模式将被应用在
最n - 1次,数组的长度不会大于n,并且
数组的最后一个条目将包含所有输入超出最后匹配的
分隔符。如果n是非正值,那么该模式将尽可能多次应用
,并且该数组可以有任意长度。如果n为零
,那么该模式将尽可能多次应用,数组
可以有任意长度,并且尾随的空字符串将被丢弃。



Groovy split seems to be ignoring empty fields.

Here is the code:

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

prints only..

abc abc

It seems to ignore empty fields. How do I retrieve empty fields using split?

解决方案

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

Second, you can achieve what you need by using the generic split(regex, int limit) as below:

def line = "abc,abc,,,"

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

Note:-
The string array you would end up in the print would throw a compilation error when asserted. But you can use the result as a normal list.

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

I would rather use limit 0 or the overloaded split to discard unwanted empty strings.

Explanation on using -1 as limit:
Stress on the below statements from 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.

这篇关于Groovy分割csv和空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆