关于Java Split 命令解析Csv 文件 [英] Regarding Java Split Command Parsing Csv File

查看:28
本文介绍了关于Java Split 命令解析Csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的 csv 文件.

I have a csv file in the below format.

H,"TestItems_20100107.csv",07/01/2010,20:00:00,"TT1198","MOBb","AMD",NEW,,

我要求 split 命令忽略双引号内的逗号.所以我使用了之前帖子中的以下 split 命令.粘贴我使用此命令的 URL

I require the split command to ignore the commas inside the double quotes . So i used the below split command from an earlier post. Pasted the URL that i took this command

String items[] = line.split(",(?=([^"]*"[^"]*")*[^"]*$)");
System.out.println("items.length"+items.length);

Java:分割逗号- 分隔字符串但忽略引号中的逗号

当我运行此 CSV 数据时,我将 items.length 打印为 8.NEW"之后行尾的最后两个逗号被忽略.我希望 split 命令获取这些逗号并将长度返回为 10.如果它在末尾,它不会获取空逗号,但如果它在字符串的中间,它会获取它.不确定我需要在 split 命令中修改什么来解决这个问题.同样在 csv 文件中,文本字段内容中的双引号可以重复(例如此帐户是大"帐户)

When i run for this CSV data I am getting the items.length printed as 8. The last two commas at the end of line after "NEW" are ignored. I want the split command to pick up these commas and return me the length as 10. It's not picking up the null commas if it's in end but it's picking it up if it's in the middle of string. Not sure what i need to modify in the split command to resolve this issue. Also in the csv file Double quotes within the contents of a Text field can be repeated (e.g. "This account is a ""large"" one")

推荐答案

正则表达式没有任何问题.问题是 split 在末尾丢弃空匹配:

There's nothing wrong with the regular expression. The problem is that split discards empty matches at the end:

这个方法就像调用二元分割法给定的表达式和极限参数零.尾随空字符串是因此不包括在结果数组.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

一种解决方法是提供一个大于您在 CSV 文件中预期的列数的参数:

A workaround is to supply an argument greater than the number of columns you expect in your CSV file:

 String[] tokens = line.split(",(?=([^"]*"[^"]*")*[^"]*$)", 99);

这篇关于关于Java Split 命令解析Csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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