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; }
source share