
Java 15+ text blocks can be cleanly split into individual lines using split("\R"), which handles all Unicode line terminators reliably—unlike or alone. This approach preserves leading/trailing whitespace per line and works across platforms.
java 15+ text blocks can be cleanly split into individual lines using `split("\r")`, which handles all unicode line terminators reliably—unlike ` ` or ` ` alone. this approach preserves leading/trailing whitespace per line and works across platforms.
When working with Java text blocks (introduced in Java 15 as a preview, standardized in Java 15+), you often need to process each logical line separately—such as parsing configuration-like content or transforming structured literals. A common pitfall is using split("
") or split("
"), which fails on mixed or platform-agnostic line endings.
The robust solution is to use the R Unicode line-break matcher in String.split(). As of Java 8+, R is supported in regular expressions and matches any Unicode line break sequence—including
,
,
, u2028 (LINE SEPARATOR), u2029 (PARAGRAPH SEPARATOR), and more. Crucially, it’s portable and future-proof.
Here's how to apply it:
String textblock = """
A : 111
B : 111
C : 1111
""";
String[] lines = textblock.split("\R");
// Note: double backslash required in Java string literal to escape 'R'
for (String line : lines) {
System.out.println("[" + line + "]"); // brackets show whitespace clearly
}
Output (note preserved indentation):
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
[ A : 111] [ B : 111] [ C : 1111] [ ]
⚠️ Important notes:
- The trailing empty line (from the closing
"""on its own line) results in a final empty string element. To exclude blank or whitespace-only lines, filter them:String[] nonEmptyLines = Arrays.stream(lines) .map(String::strip) // remove leading/trailing whitespace .filter(line -> !line.isEmpty()) .toArray(String[]::new); -
split("\R")does not trim whitespace—it preserves the exact content of each line, including indentation from the text block’s alignment. This is intentional and aligns with text block semantics. - Avoid
split(" ")orSystem.lineSeparator()-based splitting unless you strictly control input origin—Ris the standard-compliant, cross-platform choice.
In summary: use textblock.split("\R") for correct, portable line splitting of Java text blocks—and post-process with strip() and filtering as needed for your domain logic.
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










