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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With