Java Language Break a string up into substrings all of a known length


The trick is to use a look-behind with the regex \G, which means "end of previous match":

String[] parts = str.split("(?<=\\G.{8})");

The regex matches 8 characters after the end of the last match. Since in this case the match is zero-width, we could more simply say "8 characters after the last match".

Conveniently, \G is initialized to start of input, so it works for the first part of the input too.