fork(1) download
  1. /* Separar texto por comas, excepto entre comillas, con expresiones regulares
  2.   Con comillas escapadas
  3.   https://es.stackoverflow.com/q/65502/127 */
  4.  
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. final String regex = ",(\"([^\\\\\"]*(?:\\\\.[^\\\\\"]*)*)\"|[^,]*)";
  13. final String text = ",aaa,\"bbb\\\"bbb\",ccc,";
  14.  
  15. final Pattern pattern = Pattern.compile(regex);
  16. final Matcher matcher = pattern.matcher("," + text);
  17. int n = 0;
  18. String elemento;
  19.  
  20. System.out.println("Texto original: " + text);
  21.  
  22. while (matcher.find()) {
  23. System.out.print ("Elemento " + ++n + ": ");
  24. if (matcher.group(2) != null)
  25. { // Elemento entre comillas?
  26. elemento = matcher.group(2); // Obtener el texto sin las comillas
  27. }
  28. else
  29. {
  30. elemento = matcher.group(1);
  31. }
  32. System.out.println(elemento);
  33. }
  34. }
  35. }
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
Texto original: ,aaa,"bbb\"bbb",ccc,
Elemento 1: 
Elemento 2: aaa
Elemento 3: bbb\"bbb
Elemento 4: ccc
Elemento 5: