Java将特殊字符串转换为数组数组

时间:2012-09-29 11:00:19

标签: java string

我想分割这个字符串

['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']

到java中的数组字符串数组?

我可以用正则表达式做,还是应该写一个递归函数来处理这个目的?

4 个答案:

答案 0 :(得分:2)

如下所示

String str= "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']";

String[] arr = str.split("\\],\\[");
String[][] arrOfArr = new String[arr.length][];
for (int i = 0; i < arr.length; i++) {
    arrOfArr[i] = arr[i].replace("[", "").replace("]", "").split(",");
}

答案 1 :(得分:1)

我无法测试这个,因为最近的崩溃消灭了我的所有程序,但我相信你可以使用JSON解析器来解析字符串。在解析之前,您可能需要将其打包在[]{}中。

答案 2 :(得分:0)

String yourString = "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12.345','01-02-2012', 'Test 2']";
yourString = yourString.substring(1, yourString.lastIndexOf("]"));
String[] arr = yourString.split("\\],\\[");

String[][] arr1 = new String[arr.length][];
int i = 0;
String regex = "(?<=['],)";   // This regex will do what you want..
for(String a : arr) {
    arr1[i++] = a.split(regex);
}

for (String[] arrasd: arr1) {
    for (String s: arrasd) {
        System.out.println(s.replace(",", ""));
    }
}

答案 3 :(得分:0)

您可以组合使用String.split和正则表达式look-behind

String str = "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']";
String[] outerStrings = str.split("(?<=]),");
String[][] arrayOfArray = new String[outerStrings.length][];

for (int i=0; i < outerStrings.length; i++) {
   String noBrackets = outerStrings[i].substring(1, outerStrings[i].length() - 1);
   arrayOfArray[i] = noBrackets.split(",");
}