文本在指定的长度后分割,但不要使用grails破坏单词 [英] Text split after a specified length but dont break words using grails

查看:52
本文介绍了文本在指定的长度后分割,但不要使用grails破坏单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字符串,需要将其解析为长度不超过50个字符的字符串数组.对于我来说,棘手的部分是确保正则表达式在50个字符之前找到最后一个空格,以使字符串之间清晰地分开,因为我不想切断单词.

I have a long string that I need to parse into an array of strings that do not exceed 50 characters in length. The tricky part of this for me is making sure that the regex finds the last whitespace before 50 characters to make a clean break between strings since I don't want 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; 
}

推荐答案

尝试一下:

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());
}

这篇关于文本在指定的长度后分割,但不要使用grails破坏单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆