在某些情况下,使用双引号解析CSV

我有csv格式:

a1,a2,a3,“a4,a5”,a6

只有字段,会有引号

使用Java,如何轻松解析这个? 我尽量避免使用开源CSV解析器作为公司策略。 谢谢。

您可以将Matcher.find与以下正则表达式一起使用:

 \ S *( “[^”] *“| [^,] *)\ S *

这是一个更完整的例子:

 String s = "a1, a2, a3, \"a4,a5\", a6"; Pattern pattern = Pattern.compile("\\s*(\"[^\"]*\"|[^,]*)\\s*"); Matcher matcher = pattern.matcher(s); while (matcher.find()) { System.out.println(matcher.group(1)); } 

看它在线工作: ideone

我遇到了同样的问题(但是在Python中),我发现解决它的一种方法,没有正则表达式,是:当你得到行,检查任何引号,如果有引号,将字符串拆分为引号,并拆分甚至在逗号上索引结果数组的结果。 奇数索引字符串应该是完整的引用值。

我不是Java编码器,所以把它作为伪代码…

 line = String[]; if ('"' in row){ vals = row.split('"'); for (int i =0; i 

或者,使用正则表达式。

这里有一些代码供你使用,我希望使用这里的代码不算开源,这是。

 package bestsss.util; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class SplitCSVLine { public static String[] splitCSV(BufferedReader reader) throws IOException{ return splitCSV(reader, null, ',', '"'); } /** * * @param reader - some line enabled reader, we lazy * @param expectedColumns - convenient int[1] to return the expected * @param separator - the C(omma) SV (or alternative like semi-colon) * @param quote - double quote char ('"') or alternative * @return String[] containing the field * @throws IOException */ public static String[] splitCSV(BufferedReader reader, int[] expectedColumns, char separator, char quote) throws IOException{ final List tokens = new ArrayList(expectedColumns==null?8:expectedColumns[0]); final StringBuilder sb = new StringBuilder(24); for(boolean quoted=false;;sb.append('\n')) {//lazy, we do not preserve the original new line, but meh final String line = reader.readLine(); if (line==null) break; for (int i = 0, len= line.length(); i < len; i++) { final char c = line.charAt(i); if (c == quote) { if( quoted && i 

下面的代码似乎运行良好,可以处理引号内的引号。

 final static Pattern quote = Pattern.compile("^\\s*\"((?:[^\"]|(?:\"\"))*?)\"\\s*,"); public static List parseCsv(String line) throws Exception { List list = new ArrayList(); line += ","; for (int x = 0; x < line.length(); x++) { String s = line.substring(x); if (s.trim().startsWith("\"")) { Matcher m = quote.matcher(s); if (!m.find()) throw new Exception("CSV is malformed"); list.add(m.group(1).replace("\"\"", "\"")); x += m.end() - 1; } else { int y = s.indexOf(","); if (y == -1) throw new Exception("CSV is malformed"); list.add(s.substring(0, y)); x += y; } } return list; }