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?

2
  • 2
    Regex is not appropriate for parsing recursive grammars such as this. You need a real parser for this. Commented Apr 20, 2013 at 7:11
  • thanks. but even not working for just splitting strPro a time? Commented Apr 20, 2013 at 7:14

1 Answer 1

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)]

Sign up to request clarification or add additional context in comments.

3 Comments

It works well; Nice, wonderful, splendid, my English expr is poor, but thank you, Keppil
(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: You can use split("(?<=\\))(?=\\()", 2), where the 2 is the maximum length of the result. This will only apply the splitting pattern once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.