This is similar question to How to split a string at every n characters or to nearest previous space, however, on the contrary to what I was expecting based on the title, that solution does not work if there is just one long word without any whitespace.
So I need a Regex which splits a string to separate lines (multiple times if needed) by max characters per line, and looking backwards n characters for a possible whitespace (break there if found, otherwise at max length)?
For example, with max line length 30 characters with 15 characters backwards whitespace lookup:
Loremipsumissimplydummytextofthe printing and typesetting industry.
That sentence's first word has a length of 32 characters. So the output should be:
Loremipsumissimplydummytextoft # Line has length of 30 char
-he printing and typesetting # Cut before the word at otherwise 30 char
industry.
So the first word should be force-cut after 30th character, as there was no whitspace. I've also added a dash '-' character on the start of the next line, because the word was forcefully cut (optionally handled by the solution I'm after).
The remaining string has a length of 28 (or 29 with the dash) before word 'industry', so at the place of 30th character there's a word, so the solution looks up for the previous whitespace within 15 characters range. That line is broken before 'industry' word.