Split函数,正则表达式与空字符串

在处理CSV文件的时候,我们总是要用Java/Scala的Split函数,但是如果CSV文件的某一行用空格的话,split函数可能不会返回我们想要的结果;

比如stackoverflow上的一个例子:

"elem1, elem2,,".split(",") = List("elem1", "elem2")
我们会发现最后的一个空格没有了;而在处理CSV的时候,我们希望得到的结果是
"elem1, elem2,,".split(",") = List("elem1", "elem2", "", "")

事实上,split函数如果发现头尾是空字符串的话,是会自动掐头去尾的。如果要禁止他掐头去尾,应该在split函数当中填上第二个参数,这个参数给一个负数即可,例如split(str, -1)
比如:

String s = "elem1,elem2,,";
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, r, o, c, e, r, i, e, s, |, a, p, p, l, e, |, 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值