Java 正则表达式解析csv文件
最近在写Java解析CSV文件,由于公司不支持javacsv第三方包,由此想到用正则表达式解析CSV文件,我参考了该作者的代码http://blog.csdn.net/notonlyforshe/article/details/7384078,做了些改动,试了还不错。
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
Pattern pattern = Pattern.compile("(,)?((\"[^\"]*(\"{2})*[^\"]*\")*[^,]*)");
String strLine = null;
while((strLine = br.readLine()) != null) {
Matcher matcher = pattern.matcher(strLine);
while(matcher.find()) {
String cell = matcher.group(2);//group(2) is ((\"[^\"]*(\"{2})*[^\"]*\")*[^,]*)
Pattern pattern2 = Pattern.compile("\"((.)*)\"");
Matcher matcher2 = pattern2.matcher(cell);
if(matcher2.find()) {
cell = matcher2.group(1);
}
//... get the cell and you analysis
}
}
I have nothing to say
其实我在回答就是抬杠了,因为内容里面有都好外面是有引号的。拆分你的时候你甚至,"拆分都可以。当然代码可读性差
如果内容里包含逗号呢?
为何不用split呢,整个csv不就是换行和逗号组成的吗
String line = "1,2"; String columns = line.split(",",-1);