fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.regex.*;
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String input = "Jim ate a [sandwich] with [pickles] and [dried [onions]] and ] [an[other] match]";
  13. List<String> balanced = getBalancedSubstrings(input, '[', ']', true);
  14. System.out.println("Balanced ones: " + balanced);
  15. List<String> rx_split = new ArrayList<String>();
  16. for (String item : balanced) {
  17. rx_split.add("\\s*" + Pattern.quote(item) + "\\s*");
  18. }
  19. String rx = String.join("|", rx_split);
  20. System.out.println("In-betweens: " + Arrays.toString(input.split(rx)));
  21. }
  22. public static List<String> getBalancedSubstrings(String s, Character markStart, Character markEnd, Boolean includeMarkers) {
  23. List<String> subTreeList = new ArrayList<String>();
  24. int level = 0;
  25. int lastOpenBracket = -1;
  26. for (int i = 0; i < s.length(); i++) {
  27. char c = s.charAt(i);
  28. if (c == markStart) {
  29. level++;
  30. if (level == 1) {
  31. lastOpenBracket = (includeMarkers ? i : i+1);
  32. }
  33. }
  34. else if (c == markEnd) {
  35. if (level == 1) {
  36. subTreeList.add(s.substring(lastOpenBracket, (includeMarkers ? i+1 : i)));
  37. }
  38. if (level > 0) level--;
  39. }
  40. }
  41. return subTreeList;
  42. }
  43. }
Success #stdin #stdout 0.06s 27888KB
stdin
Standard input is empty
stdout
Balanced ones: [[sandwich], [pickles], [dried [onions]], [an[other] match]]
In-betweens: [Jim ate a, with, and, and ]]