2

I have a string like

String str = "(3456,"hello", world, {ok{fub=100, fet = 400, sub="true"}, null }, got, cab[{m,r,t}{u,u,r,}{r,m,"null"}], {y,i,oft{f,f,f,f,}, tu, yu, iu}, null, null)

Now I need to split this string based on comma(,) but the strings which are between {} and [] should not be split. So my out put should look like

3456
hello
world
{ok{fub=100, fet = 400, sub="true"}, null}
got
cab[{m,r,t}{u,u,r,}{r,m,"null"}]
{y,i,oft{f,f,f,f,}, tu, yu, iu}
null
null

I know that it looks strange, I can do it by using old traditional brute force methods, but I need if there is any simplest logic for these kind of problems.

Can any one help me?

Thanks in advance :-)

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • 2
    Your `String` is very close to markup conceptually. You should probably consider not using regular expressions to split it - at least not on the long run. – Mena Apr 28 '15 at 11:11
  • 2
    http://stackoverflow.com/a/26329550/1393766 – Pshemo Apr 28 '15 at 11:13
  • 1
    This is like parsing xml using regex... possible, but hard to make correct while more simple methods are available. – Alex Salauyou Apr 28 '15 at 11:16
  • 1
    Clearly it is not possible to deal with nested structures with Java regex, since it doesn't have one of these tools: the recursion, the balancing groups. – Casimir et Hippolyte Apr 28 '15 at 11:20

1 Answers1

2
// Assuming open brackets have corresponding close brackets
int brackets = 0;
int currIndex = 0;
List<String> output = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
    if (isOpenBracket(str.charAt(i))) {
        brackets++;
    } else if (isCloseBracket(str.charAt(i))) {
        brackets--;
    } else if (str.charAt(i) == ',') {
        output.add(str.substring(currIndex, i));
        currIndex = i + 1;
    }
}
output.add(currIndex, str.length());
return output;

Would this work?

M. Shaw
  • 1,742
  • 11
  • 15