java - 按 {} 和 [] 拆分字符串

标签 java regex string split

我是 Java 的新手。 我想知道是否有更简单而有效的方法来实现以下字符串拆分。我已经尝试过模式和匹配器,但并没有真正按照我想要的方式出现。

"{1,24,5,[8,5,9],7,[0,1]}"

拆分成:

1 
24
5
[8,5,9]
7
[0,1]

这是一个完全错误的代码,但我还是发布了它:

    String str = "{1,24,5,[8,5,9],7,[0,1]}";
    str= str.replaceAll("\\{", "");
    str= str.replaceAll("}", "");
    Pattern pattern = Pattern.compile("\\[(.*?)\\]");
    Matcher matcher = pattern.matcher(str);
    String[] test = new String[10];
   // String[] _test = new String[10];
    int i = 0;
    String[] split = str.split(",");

    while (matcher.find()) {


        test[i] = matcher.group(0);
        String[] split1 = matcher.group(0).split(",");


      // System.out.println(split1[i]);
           for (int j = 0; j < split.length; j++) {
             if(!split[j].equals(test[j])&&((!split[j].contains("\\["))||!split[j].contains("\\]"))){
              System.out.println(split[j]);
             }

        }
        i++;


    }

}

对于给定的字符串格式,可以说是 {a,b,[c,d,e],...} 格式。我想征集所有内容,但方括号中的内容将表示为一个元素(如数组)。

最佳答案

这个有效:

  public static void main(String[] args)
  {
     customSplit("{1,24,5,[8,5,9],7,[0,1]}");
  }


  static void customSplit(String str){
     Pattern pattern = Pattern.compile("[0-9]+|\\[.*?\\]");
     Matcher matcher =
           pattern.matcher(str);
     while (matcher.find()) {
        System.out.println(matcher.group());
     }
  }

产生输出

1
24
5
[8,5,9]
7
[0,1]

关于java - 按 {} 和 [] 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17276491/

相关文章:

java - 将两个椭圆拟合到 body 轮廓

Java 正则表达式 : To know the number of rows to be returned by a SQL Query

java - 根据txt文件夹打印星星

Java简单日期格式化程序解析远程机器中的异常

python - 在 python 正则表达式中使用 OR 的最佳方法是什么

javascript - 适用于所有 Discord 标签类型的正则表达式模式

php - 为什么 PHP 忽略任何字符串开头的换行符

Javascript正则表达式匹配有界文本

java - 正则表达式 - 检查子字符串是否不是模式的一部分

regex - Perl 中的十六进制数的按位非