In this guide, you will learn how to split string by newline in Java. The newline character is different for various operating systems, so I will try to cover the java code for most of the operating systems such as Mac OS, Windows, Unix and Linux.
How to Split String by Newline in Java
1. Using System.lineSeparator() method
This is one of the best way to split string by newline as this is a system independent approach. The lineSeparator() method returns the character sequence for the underlying system. The newline regular expression for various operating system as follows:
This is how you can call the System.lineSeparator() method:
String[] str = "Text\r\nText\r\nText".split(System.lineSeparator());
This will produce the following output for all operating systems:
["Text", "Text", "Text"]
2. Using String.split() method
I have already covered split() method in detail. Here, we are using the split() method of Java String class to split string by newline in various operating system. We will pass the newline character as a regular expression. The newline regular expression for various operating system as follows:
- \\n : For Unix, Linux and Mac OS.
- \\r\\n : For Windows
- \\r : For older version of Mac OS (prior to Mac OS 9)
Unix, Linux and Mac OS (latest versions):
String[] str = "Text\nText\nText".split("\\r?\\n|\\r");
Windows:
String[] str = "Text\r\nText\r\nText".split("\\r?\\n|\\r");
Older version of Mac OS:
String[] str = "Text\rText\rText".split("\\r?\\n|\\r");
All these will produce the following output in corresponding operating systems:
["Text", "Text", "Text"]
3. Using \R Pattern in Java 8 or higher
If you are using Java 8 or higher then you can use the \R
pattern instead of "\\r?\\n|\\r"
. The \R pattern is system independent and works in all the Operating Systems.
You can call the split() method to split string by newline in Java 8 or higher like this:
Unix, Linux and Mac OS (latest versions):
String[] str = "Text\nText\nText".split("\\R");
Windows:
String[] str = "Text\r\nText\r\nText".split("\\R");
Older version of Mac OS:
String[] str = "Text\rText\rText".split("\\R");
4. Using lines() method of String class
In Java 11, a new method lines()
has been added to the String class. This method internally uses \R
pattern to match the newline of the underlying operating system.
Stream<String> str = "Text\nText\r\nText".lines();
If you want string array as output then use this code:
String[] strArray = "Text\nText\r\nText".lines().toArray(String[]::new);
FAQ
The lineSeparator() is pre-defined method that belongs to System class in Java. It returns the new line string for the underlying operating system.
To split a string by newline , you can use split(“\\r?\\n|\\r”) regular expression. For java 8 or higher you can replace this regex with split(“\\R”).