If I understand your problem correctly, this code should do what you need (but assumes maxLenght is equal to or greater than the long word )
String data = "Hello there, my name is not importnant right now." + " I am just simple sentecne used to test few things."; int maxLenght = 10; Pattern p = Pattern.compile("\\G\\s*(.{1,"+maxLenght+"})(?=\\s|$)", Pattern.DOTALL); Matcher m = p.matcher(data); while (m.find()) System.out.println(m.group(1));
Exit:
Hello there, my name is not importnant right now. I am just simple sentecne used to test few things.
A brief (or not) explanation of "\\G\\s*(.{1,"+maxLenght+"})(?=\\s|$)" regex:
(let's just remember that in Java \ not only special in regular expression, but also in string literals, so to use predefined character sets like \d , we need to write it as "\\d" , because we need was to escape that \ also in a string literal)
Thus, thanks to .{1,10} we can match up to 10 characters. But after (?=\\s|$) after that, we require that the last character matched .{1,10} should not be part of an incomplete word (there must be a space or the end of a line after it).
Pshemo
source share