I was curious on how it would be possible to split mathematical equations with parenthesis meaningfully using java’s string regex. It’s hard to explain without an example, one is below.
A generic solution pattern would be appreciated, rather than one which just works for the example provided below.
String s = "(5 + 6) + (2 - 18)";
// I want to split this string via the regex pattern of "+",
// (but only the non-nested ones)
// with the result being [(5 + 6), (2 - 18)]
s.split("\\+"); // Won't work, this will split via every plus.
What I’m mainly looking for is first level splitting, I want a regex check to see if a symbol like “+” or “-” is nested in any form, if it is, don’t split it, if it isn’t split it. Nesting can be in the form of () or [].
Thank you.
If you don’t expect splitting nested expressions like ((6 + 5)-4), I have a pretty simple function to split the expressions without using regular expressions :
Sample output :Original expression : (a+b)+(5+6)+(57-6)
Sub expressions : [ (a+b), (5+6), (57-6), ]
EDIT
For the extra condition of also getting expressions enclosed in
[], this code will handle expressions inside both()and[].Sample Output :Original expression : (a+b)+[5+6]+(57-6)-[a-b]+[c-d]
Sub expressions : [ (a+b), [5+6], (57-6), [a-b], [c-d], ]
Do suggest improvements in the code. 🙂