有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将字符串切碎成这样的数组?

我正在尝试拆分一个字符串,如下所示:

[a05, [a24, a23], [b08, b09], c26, c30, a22, a13, m06]

分为以下几个部分:

a05
[a24, a23]
[b08, b09]
c26
c30
a22
a13
m06

也就是说,在,上拆分,但将[...]视为一个标记,即使它包含,


共 (2) 个答案

  1. # 1 楼答案

    下面是一种使用正则表达式的方法:

    String input = "[a05, [a24, a23], [b08, b09], c26, c30, a22, a13, m06]";
    
    // Strip outer [...]
    String content = input.substring(1, input.length() - 1);
    
    List<String> parts = new ArrayList<>();
    Matcher m = Pattern.compile("\\[.*?\\]|[^\\[, ]+").matcher(content);
    while (m.find()) {
        parts.add(m.group());
    }
    parts.forEach(System.out::println);
    

    输出

    a05
    [a24, a23]
    [b08, b09]
    c26
    c30
    a22
    a13
    m06
    

    正则表达式细分:

    • \[.*?\]形式上的某物[...]
    • |
    • [^\[, ]+一个或多个不是[,或空格的字符

    也许我把你的例子看得太字面了。如果上述情况不起作用,请随意用更复杂的情况扩展您的示例

    关于正则表达式的注记

    请注意,正则表达式所能表达的内容非常有限,只有在输入相当可预测时才适用。如果您发现需要任意嵌套括号[...[...]...]或类似的情况,您必须做更多的工作。“下一步”可能是“手动”循环/解析输入,或者编写上下文无关语法并使用解析器生成器

  2. # 2 楼答案

    首先导入arrayList

    import java.util.ArrayList;

    我们需要这个到最后的结果转换

    boolean check = false;
        ArrayList<String> result = new ArrayList<String>();
        String yourString =  "[a05, [a24, a23], [b08, b09], c26, c30, a22, a13, m06]";
        // we need to remove the first char "[" and the last char "]"
        yourString = yourString.substring(0, yourString.length() - 1);
        yourString = yourString.substring(1, yourString.length());
        // and then, we need to split
        String[] parts = yourString.split(", ");
        String temp = "";
        for(int i =0;i<parts.length;i++){
          if(parts[i].contains("[")){
            check = true;
            temp += parts[i] +", ";
          }
          else if(check == false){
            result.add(parts[i]);
          }
    
          else if(parts[i].contains("]")){
            temp += parts[i];
            result.add(temp);
            temp = "";
            check = false;
          }
          else if(check == true){
            temp += parts[i]+", ";
          }
        }
        System.out.println(result.size());
        for(int i =0;i<result.size();i++){
          System.out.println(result.get(i));
        }