fork download
  1. import java.util.regex.*;
  2. import java.util.*;
  3.  
  4. class T {
  5. public static String join(String sep, Iterable<String> it) {
  6. String joined = "";
  7. boolean first = true;
  8.  
  9. for (String s : it) {
  10. if (first)
  11. first = false;
  12. else
  13. joined += sep;
  14. joined += s;
  15. }
  16. return joined;
  17. }
  18.  
  19. public static Iterable<String> split(String s) {
  20. List<String> result = new LinkedList<String>();
  21. Stack<String> stack = new Stack<String>();
  22. Pattern pattern = Pattern.compile("[,\\[\\]]|.+?");
  23. Matcher matcher = pattern.matcher(s);
  24.  
  25. stack.push("");
  26. while (matcher.find()) {
  27. String token = matcher.group();
  28. if (token.equals("[")) {
  29. stack.push("");
  30. } else if (token.equals("]")) {
  31. if (! stack.peek().isEmpty())
  32. result.add(join(".", stack));
  33. stack.pop();
  34. stack.pop();
  35. stack.push("");
  36. } else if (token.equals(",")) {
  37. if (! stack.peek().isEmpty())
  38. result.add(join(".", stack));
  39. } else {
  40. stack.pop();
  41. stack.push(token);
  42. }
  43. }
  44. if (! (stack.isEmpty() || stack.peek().isEmpty()))
  45. result.add(join(".", stack));
  46. return result;
  47. }
  48.  
  49. public static void main(String[] args) {
  50. String text = "a,b,c[a,b,c[a]],d";
  51. for (String s : split(text))
  52. System.out.println(s);
  53. }
  54. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
a
b
c.a
c.b
c.c.a
d