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?

2
  • Why you want to use Regex, if you can do it with simple split?? Commented Sep 29, 2012 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 Commented Sep 29, 2012 at 11:05

4 Answers 4

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(",");
}
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
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

1 Comment

Thanks for your help I did it with JSON ObjectMapper
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(",");
}

Comments

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(",", ""));
    }
}

1 Comment

@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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.