1

I want to split this string

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

To an array of array string in java?

Can I do it with regex or should I write a recursive function to handle this purpose?

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
AKZ
  • 856
  • 2
  • 12
  • 30
  • Why you want to use Regex, if you can do it with simple `split`?? – Rohit Jain Sep 29 '12 at 11:01
  • i want to have an array of array for example for this string array[1][2] should give me BR_1142. I don't know how can i do it with split? thanks for help – AKZ Sep 29 '12 at 11:05

4 Answers4

2

How about something like the following

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(",");
}
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • @AKZ, you're right. You could try `split("','")` though that would also remove the `'` chars. I'm sure you can find an approach from there. – Johan Sjöberg Sep 29 '12 at 11:38
1

I'm not able to test this because of recent crash wiped out all my programs, but I believe you can use the JSON parsers to parse the string. You might have to wrap it in [ and ] or { and } before you parse.

See

Community
  • 1
  • 1
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
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(",", ""));
    }
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • @AKZ.. Also, if you try to retain `,` in between `12,345` from the above process, you will loose the other `'`.. So, I have replaced them with "" to remove them completely.. – Rohit Jain Sep 29 '12 at 11:46
0

You could use String.split and regex look-behind in combination:

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(",");
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276