如何使用逗号分割字符串,但在{...}的逗号中没有任何字符串

时间:2011-03-20 02:57:17

标签: java

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);
}

我希望拆分字符串filterPath,但不包含任何{...}的逗号:

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

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);
}