我有一个很长的字符串,需要将其解析为长度不超过 50 个字符的字符串数组。这对我来说棘手的部分是确保正则表达式找到 50 个字符之前的最后一个空格,以便在字符串之间进行干净的分隔,因为我不希望单词被截断。
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;
}
最佳答案
试试这个:
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());
}
关于java - 文本在指定长度后拆分,但不要使用 grails 打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9661823/