fork download
  1. /* Parsear csv con comillas problematicas
  2.   https://es.stackoverflow.com/q/65958/127 */
  3.  
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. class Ideone
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. final String[] csv = new String[] {
  12. ",codigo,nom,cognom",
  13. ",111,michael,salinas",
  14. ",222,\"luis\",\"doh, \\”jik\"",
  15. ",333,ram,\"Lak\"\"\\\"\"\"\"\\\"\"\"\"\\\"\" , \"\"\\\"\"“one\""
  16. };
  17.  
  18. final String regex = ",(\"[^\"]*(?:\"\"[^\"]*)*\"|[^,]+)";
  19. final Pattern pattern = Pattern.compile(regex);
  20.  
  21. for (String line : csv) {
  22. System.out.println("Línea: " + line);
  23.  
  24. final Matcher m = pattern.matcher(line);
  25.  
  26. while (m.find()) {
  27. System.out.println(" Elemento: " + m.group(1));
  28. }
  29. }
  30. }
  31. }
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
Línea: ,codigo,nom,cognom
  Elemento: codigo
  Elemento: nom
  Elemento: cognom
Línea: ,111,michael,salinas
  Elemento: 111
  Elemento: michael
  Elemento: salinas
Línea: ,222,"luis","doh, \”jik"
  Elemento: 222
  Elemento: "luis"
  Elemento: "doh, \”jik"
Línea: ,333,ram,"Lak""\""""\""""\"" , ""\""“one"
  Elemento: 333
  Elemento: ram
  Elemento: "Lak""\""""\""""\"" , ""\""“one"