1
String filterPath="aa.bb.cc{k1:v1,k2:{s1:s2}},bb.cc,ee.dd";

String[] result=filterPath.split(",");
for(String r:result){
    System.out.println(r);
}

I want split the String filterPath ,but with out any in { ... }'s commas:

aa.bb.cc{k1:v1,k2:{s1:s2}}
bb.cc
ee.dd

thanks for help.

Koerr
  • 15,215
  • 28
  • 78
  • 108
  • Is there a possibility of nested `{}`s? – jswolf19 Mar 20 '11 at 03:01
  • possible duplicate of [How can you parse the string which has a text qualifier](http://stackoverflow.com/questions/3178008/how-can-you-parse-the-string-which-has-a-text-qualifier) – Lou Franco Mar 20 '11 at 03:01
  • @Lou: I don't think this is a duplicate. The algorithm to look for matching quotes is different than the one to look for matching braces, particularly if the braces can be nested. – Gabe Mar 20 '11 at 03:27
  • {...} is JSON String,is there a possibility of nested, my String is: `path{JSON},path{JSON}...` – Koerr Mar 20 '11 at 03:37

1 Answers1

1

Here's one way:

String filterPath = "aa.bb.cc{k1:v1,k2:{s1:s2}},bb.cc,ee.dd";

List<String> result = new ArrayList<String>();
StringBuilder build = new StringBuilder();
int skip = 0;

for (char c : filterPath.toCharArray()) {
    if (c == ',' && skip == 0) {
        result.add(build.toString());
        build = new StringBuilder();
        continue;
    }

    if (c == '{') {
        skip++;
    } else if (c == '}') {
        skip--;
    }

    build.append(c);
}

result.add(build.toString());

for (String r : result) {
    System.out.println(r);
}
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • thanks for help,I edited my question,the String is JSON String, may be:`aa.bb.cc{k1:v1,k2:{s1:s2}},bb.cc,ee.dd` – Koerr Mar 20 '11 at 03:41
  • 1
    you need to make skip a int/uint rather than a boolean or you'll have trouble with the nested braces. Try for example `aa.bb.cc{k1:v1,k2:{s1:s2},k3:v3},bb.cc,ee.dd` – jswolf19 Mar 21 '11 at 05:33