Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string into groups?

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.

like image 518
AncientSwordRage Avatar asked Mar 23 '23 08:03

AncientSwordRage


2 Answers

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!

like image 103
Sazzadur Rahaman Avatar answered Apr 01 '23 22:04

Sazzadur Rahaman


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.

  1. Use a stack
  2. While reading the original string push all the characters into the stack
  3. now popup one by one from the stack by using following logic a. if get ) start adding to a string b. if get ( add to the string and now you get one token. add the token to the array. c. after getting ( skip till the next ).

N.B. it's just and pseudo code with primitive thinking.

like image 39
stinepike Avatar answered Apr 01 '23 21:04

stinepike