Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string into n-length elements for an array [duplicate]

How would I split a string into equal parts using String.split() provided the string is full of numbers? For the sake of example, each part in the below is of size 5.

"123" would be split into "123"
"12345" would be split into "12345"
"123451" would be split into "12345" and "1"
"123451234512345" would be split into "12345", "12345" and "12345"
etc

These are to be put in an array:

String myString = "12345678";
String[] myStringArray = myString.split(???);
//myStringArray => "12345", "678";

I'm just unsure the regex to use, nor how to separate it into equal sized chunks.

like image 420
gator Avatar asked Mar 20 '23 07:03

gator


1 Answers

You can try this way

String input = "123451234512345";
String[] pairs = input.split("(?<=\\G\\d{5})");
System.out.println(Arrays.toString(pairs));

Output:

[12345, 12345, 12345]

This regex uses positive look behind mechanism (?<=...) and \\G which represents "previous match - place where previously matched string ends, or if it doesn't exist yet (when we just started matching) ^ which is start of the string".

So regex will match any place that has five digits before it and before this five digits previously matched place we split on.

like image 157
Pshemo Avatar answered Mar 22 '23 21:03

Pshemo