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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Java Language Question?