You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java正则分割字符串:如何保留换行符而非合并为空白

Java字符串分割时保留换行符的解决方案

给定经RabbitMQ传递的Java字符串:

"word1 word2! word3? word4; word5, word6\nword7\n!word8! word9 word10 word11 word12"

需求是分割该字符串时保留换行符(\n),不能将其与普通空白(空格)混为一谈当作分隔符。当前使用s.split("[\\s\\r\\n]")得到的结果中出现空字符串,根源是换行符被当作普通分隔符处理。

方案1:正则匹配提取目标元素(推荐)

放弃使用split,直接匹配所有需要保留的内容——包括带标点的单词和换行符,既能精准保留换行符,又能避免空元素:

import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class SplitWithNewLine {
    public static void main(String[] args) {
        String input = "word1 word2! word3? word4; word5, word6\nword7\n!word8! word9 word10 word11 word12";
        String[] splitResult = Pattern.compile("[^\\s]+|\\n")
                .matcher(input)
                .results()
                .map(MatchResult::group)
                .toArray(String[]::new);
        
        // 打印验证结果
        for (String item : splitResult) {
            System.out.println("'" + item + "'");
        }
    }
}

运行后输出结果:

'word1'
'word2!'
'word3?'
'word4;'
'word5,'
'word6'
'\n'
'word7'
'\n'
'!word8!'
'word9'
'word10'
'word11'
'word12'

正则表达式[^\\s]+|\\n的逻辑:

  • [^\\s]+:匹配任意非空白字符的连续序列(即带标点的单词)
  • |\\n:或者匹配单独的换行符,将其作为独立元素保留

方案2:调整split的正则表达式

如果必须使用split方法,可以通过零宽断言实现仅在普通空白处分割,同时保留换行符:

String input = "word1 word2! word3? word4; word5, word6\nword7\n!word8! word9 word10 word11 word12";
String[] splitResult = input.split("\\s(?!\\n)|(?<=\\n)|(?=\\n)");

注意:该方案可能在字符串首尾为换行符时产生空元素,需要额外过滤空字符串。

内容的提问来源于stack exchange,提问作者Ivan Dvurechenskiy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:12:29