views:

118

answers:

3

I have a following string that I would like to parse into either a List or a String[].

(Test)(Testing (Value))

End result should be Test and Testing (Value)

+2  A: 

If I understood correctly that you need Test and Testing (Value), then here is regexp:

\(([^\)]+)\)\((.+)\)

and masked version of it ready for java string:

\\(([^\\)]+)\\)\\((.+)\\)
serg
This cannot handle unlimited nesting.
SLaks
@SLaks Well, it handles his exact question, although so does `return new String[] {"Test", "Testing (Value)"};`. It's unclear exactly how generic the solution needs to be
Michael Mrozek
Who said anything about unlimited nesting? And this one would capture `Testing (V(a(l)u)e)` into second captured group, if that's what you mean (and if that's what is needed as it is not clear from the question).
serg
Yep the solution by serg555 is exactly what I was looking for. Sorry for not being clear. Thanks!
A: 

Please read this section of php manual. It tells you about recursive patterns, which can be used to match nested things, and about the related problems. Google it for more information.

scaryzet
You might want to include a synopsis or quote from the article you linked to. That way we have a clue as to why we should follow your link.
chilltemp
@chilltemp: It doesn't really matter in this case; the OP is working in Java, which has no support for recursive regexes.
Alan Moore
A: 

This question is really vague, but under one reasonable interpretation, this is the solution that can take care of arbitrary nesting depth in a certain format:

    String text = "(T)(T(V))(1(2(3)2)1)(a*(b+(c-d))+(e/f))";
    String[] parts = text.split("(?<=\\))(?=\\()");
    System.out.println(java.util.Arrays.toString(parts));
    // prints "[(T), (T(V)), (1(2(3)2)1), (a*(b+(c-d))+(e/f))]"

Basically you want to split between )( (using assertions). Won't work for all cases, e.g. ((.)(.)), but like many people have said, the requirements of the question is vague, and the general balanced parenthesis problem is not solvable with Java regex.

See also

polygenelubricants