最近在写Java解析CSV文件,由于公司不支持javacsv第三方包,由此想到用正则表达式解析CSV文件,我参考了该作者的代码[url]http://blog.youkuaiyun.com/notonlyforshe/article/details/7384078[/url],做了些改动,试了还不错。
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
}
}