The text is divided by a given length, but does not break the words using a rake

I have a long string that I need to parse into an array of strings no more than 50 characters long. The hard part for me is to make sure that the regular expression finds the last spaces before 50 characters to make a clean line break, since I don't want the words cut off.

public List<String> splitInfoText(String msg) { int MAX_WIDTH = 50; def line = [] String[] words; msg = msg.trim(); words = msg.split(" "); StringBuffer s = new StringBuffer(); words.each { word -> s.append(word + " "); if (s.length() > MAX_WIDTH) { s.replace(s.length() - word.length()-1, s.length(), " "); line << s.toString().trim(); s = new StringBuffer(word + " "); } } if (s.length() > 0) line << s.toString().trim(); return line; } 
+6
source share
2 answers

Try the following:

 List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile(".{1,50}(?:\\s|$)", Pattern.DOTALL); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { matchList.add(regexMatcher.group()); } 
+5
source

I believe the version of Grover Tim's answer:

 List matchList = ( subjectString =~ /(?s)(.{1,50})(?:\s|$)/ ).collect { it[ 1 ] } 
+4
source

Source: https://habr.com/ru/post/910469/


All Articles