拆分一个 "array"-like 字符串

Split an "array"-like string

我想从类似于 "array" 的字符串(来自文件)中提取一些数据,即:

PR=[[20,5],[24,11],[24,13]]

此外,我想将数据存储到一个实际的数组中,我的意思是:

int[][] pr = {{20,5},{24,11},{24,13}};

编辑:我可以使用 Regex 或类似的东西吗?

你可以使用很多JSON库,注意你需要创建相应的class和对象才能反序列化JSON字符串。

下面演示如何使用 Gson 来实现:

import com.google.gson.Gson;

class Matrix implements Serializable {
    Integer[][] matrix;
    Matrix(){};

    public static  void main(String[] args) {
        Gson gson = new Gson();
        Matrix matrix = gson.fromJson("{\"matrix\" : [[20,5],[24,11],[24,13]]}", Matrix.class);
        System.out.println("matrix = \n" + matrix);

    }

    public String toString() {
        String res = "";
        if (matrix == null)
            return res;

        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[0].length; j++) {
                res += matrix[i][j] + ",";
            }
            res += "\n";
        }
        return res;
    }
}

输出

matrix = 
20,5,
24,11,
24,13,