1

This is the string:

String strPro = "(a0(a1)(a2 and so on)...(aN))";

Content in a son-() may be "", or just the value of strPro, or like that pattern, recursively, so a sub-() is a sub-tree.

Expected result:

str1 is "a0(a1)"
str2 is "(a2 and so on)"
...
strN is "(aN)"

str1, str2, ..., strN are e.g. elements in an Array

How to split the string?

Mario Kutlev
  • 4,897
  • 7
  • 44
  • 62
droidpiggy
  • 15
  • 3

1 Answers1

1

You can use substring() to get rid of the outer paranthesis, and then split it using lookbehind and lookahead (?<= and ?=):

String strPro = "(a0(a1)(a2 and so on)(aN))";
String[] split = strPro.substring(1, strPro.length() - 1).split("(?<=\\))(?=\\()");
System.out.println(Arrays.toString(split));

This prints

[a0(a1), (a2 and so on), (aN)]

Keppil
  • 45,603
  • 8
  • 97
  • 119
  • It works well; Nice, wonderful, splendid, my English expr is poor, but thank you, Keppil – droidpiggy Apr 20 '13 at 07:21
  • (S(B1)(B2(B21)(B22)(B23))) --> I need only S(B1) and B2(B21)(B22)(B23)), first level, not four elements, how can I reach this? – droidpiggy Apr 22 '13 at 06:38
  • @droidpiggy: You can use `split("(?<=\\))(?=\\()", 2)`, where the `2` is the maximum length of the result. This will only apply the splitting pattern once. – Keppil Apr 23 '13 at 04:47