【问题标题】:how to split the String using comma,but with out any in {...}'s commas如何使用逗号分割字符串,但在 {...} 的逗号中没有任何内容
【发布时间】:2011-03-20 02:57:16
【问题描述】:
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

感谢您的帮助。

【问题讨论】:

  • 有没有可能嵌套{}s?
  • @Lou:我不认为这是重复的。查找匹配引号的算法与查找匹配大括号的算法不同,尤其是在大括号可以嵌套的情况下。
  • {...} 是 JSON 字符串,有没有嵌套的可能,我的字符串是:path{JSON},path{JSON}...

标签: java


【解决方案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);
}

【讨论】:

  • 感谢帮助,我编辑了我的问题,字符串是 JSON 字符串,可能是:aa.bb.cc{k1:v1,k2:{s1:s2}},bb.cc,ee.dd
  • 你需要跳过一个 int/uint 而不是一个布尔值,否则你会遇到嵌套大括号的问题。例如aa.bb.cc{k1:v1,k2:{s1:s2},k3:v3},bb.cc,ee.dd
猜你喜欢
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多