Vijay Dev Vijay Dev - 1 month ago 8
Java Question

Splitting a string at every n-th character

In JavaScript this is how we can split a string at every 3-rd character

"foobarspam".match(/.{1,3}/g)


I am trying to figure out how to do this in Java. Any pointers?

Answer

You could do it like this:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))