jlp
jlp

Reputation: 1706

How to split a String containing multiple groups of string into Sets of Set in Java

I have a String that contains multiple groups of string, each group is wrapped in brackets {}. Each group is separated by comma and each string with a group is also separated by comma. The format is something like:

  {abc,  def}, {006,  xy,  036}, {......}

What I want to do is to put each group into a HashSet, and another HashSet contains all those sets, something like:

  set 1:  abc
          def

  set 2:  006
          xy
          036
   .....
  set n:

  allSets --> set1, set2, set...., setn.

What I can think of now is to iterate each char in the original string and add it to the set(s). But I wonder if there are other ways to do it, or if Java has some APIs that can accomplish this. Thanks a lot!

Upvotes: 0

Views: 244

Answers (1)

Rishal
Rishal

Reputation: 1538

    String str="{abc,  def}, {006,  xy,  036}";
    Pattern p = Pattern.compile("\\{(.*?)\\}");
    Matcher m = p.matcher(str);
    while (m.find()) {
      System.out.println(m.group(1));
    }

It will give you values like

abc, def
006, xy, 036

Now you can go ahead and add it accordingly into the string array or map, Its a hack around.

Upvotes: 2

Related Questions