I'm trying to work out how to split a string into groups. I don't think the split(regex)
method will suffice on it's own.
I have String complexStatement = "(this && that)||(these&&those)||(me&&you)";
and I would like an array out with this kind of form:
"(this && that)","(these&&those)","(me&&you)""
If I had "(5+3)*(2+5)+(9)"
then I'd like to have "(5+3)","(2+5)","(9)".
(bonus points if you can somehow keep the join information, e.g. *,+,||
)
Is this possible for an arbitrary string input? I'm playing with a StringTokenizer but I haven't quite gotten to grips with it yet.
You can use the bellow code:
String str = "(this && that)\",\"(these&&those)\",\"(me&&you)";
Pattern pattern = Pattern.compile("\\(([^\\)]+)\\)");
Matcher m = pattern.matcher(str);
while (m.find()){
System.out.println(m.group(0));
}
\\(([^\\)]+)\\)
will dig you anything within the parenthesis, look like what you want!:
Edit:
To capture content between )
and (
just replace the regular expression with \\)([^\\(]+)\\(
this one!
I think you better implement the parsing instead of depending on any ready-made methods.
Here is my suggestion... I am assuming the format of input will be always like followig
(value1+operator+value2)+operator+(value3+operator+value4)+........
[here operator can be different, and + is just showing concatanation).
If the above assumptio is true then you can do the following.
N.B. it's just and pseudo code with primitive thinking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With