在处理CSV文件的时候,我们总是要用Java/Scala的Split函数,但是如果CSV文件的某一行用空格的话,split函数可能不会返回我们想要的结果;
比如stackoverflow上的一个例子:
"elem1,elem2,".split(",") = List("elem1","elem2")
我们会发现最后的一个空格没有了;而在处理CSV的时候,我们希望得到的结果是
"elem1,"elem2","","")
事实上,split函数如果发现头尾是空字符串的话,是会自动掐头去尾的。如果要禁止他掐头去尾,应该在split函数当中填上第二个参数,这个参数给一个负数即可,例如split(str,-1)
比如:
String s = "elem1,";
String[] tokens = s.split(",",-1);
Java文档中对于split函数的第二个参数limit做了如下解释:
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.
简而言之,就是如果是正数的话,就只用这么多次;如果是负数的话,就能用几次用几次;如果是0,还是能用几次用几次,但是头尾的空字符串会被扔掉。
另外,今天看到一个问题:有人想用“|”这个符号来作为分隔符,却怎么都不对:
val s = "Pedro|groceries|apple|1.42"
s: java.lang.String = Pedro|groceries|apple|1.42
scala> s.split("|")
res27: Array[java.lang.String] = Array("",P,e,d,r,o,|,g,c,i,s,a,p,l,1,.,4,2)
其原因在于,当split函数的第一个参数传进一个String的时候,split函数会认为这个参数是一个正则式,而“|”符号在正则式里面是“或”的符号,所以“|”被split解读为“空字符串 或 空字符串”,结果就出现了问题。正确的做法是应该传'|'
,即用单引号括起来,或者用\进行转义。
来源:
1. http://stackoverflow.com/questions/27689065/how-to-split-string-with-trailing-empty-strings-in-result
2. http://stackoverflow.com/questions/11284771/scala-string-split-does-not-work