Below is the example of the code snippet which needs the help
Example:
[1,2,3,4,5]
1
,
This should do the trick
public static List split(String string, int chunk) {
Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
+ "}[0-9]+)|[0-9]+");
Matcher matcher = pattern.matcher(string);
List result = new ArrayList();
while (matcher.find())
result.add("[" + matcher.group() + "]");
return result;
}
Test code:
for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
System.out.println("test for chunk size: " + chunkSize);
for (String string : split("[1,2,3,4,5]", chunkSize))
System.out.format("\t%s\n", string);
}
Output:
test for chunk size: 1
[1]
[2]
[3]
[4]
[5]
test for chunk size: 2
[1,2]
[3,4]
[5]
test for chunk size: 3
[1,2,3]
[4]
[5]
test for chunk size: 4
[1,2,3,4]
[5]
test for chunk size: 5
[1,2,3,4,5]