How to split String by newline in java

Split String by new line in java

In this post, we will see how to split String by newline in java.

Splitting a string by a newline character is one of the most common string operations performed in java, broadly there are two ways of achieving this task as mentioned below.

While considering new line characters, it is important to understand that the character differs based on the operating system, and the regular expression must be formed in such a way that it covers new line characters for all the operating systems, so that the code is not platform dependent.

Let’s now take a look at different operating systems and their corresponding new line characters.

Operating System
New line character
Windows
\r\n
Linux
\n
macOS
Older version \r Newer versions \n

Next, let’s start looking in detail at each method mentioned earlier in detail.

Split by new line character using regular expressions and split() method

As already discussed splitting the string by newline required us to consider the newline characters of the different operating systems so as to provide a generic platform-independent solution for the problem, This requires us to form a regex that will be zero or 1 combination of \r followed by \r or just \r based on the operating system we are considering.

Taking the above into consideration out regex will be “\r?\n|\r”.
Next, let’s try to understand this regex by understanding each of its parts.

  • \r? Zero or one \r
  • \n one \n
  • \r one \r

Note, here we are using \\ as single \ is an escape character.

Let’s see a code example for this.

Output:

[This is a simple String, , , Let’s try to split this, One more line]

If you don’t want empty space in between the line, you can use [\\r?\\n|\\r] as regex.
Here is an example:

[This is a simple String, Let’s try to split this, One more line]

Using line.separator

line.separator is a property of System class in java that provides default newline characters for the operating system let’s understand with an example below.

Output:

[First Line, Second Line]

Although, this is one of the approaches to split the string it is not recommended as it is platform dependent.

Split by new line character using regular expressions and split() method using java 8

Java 8 provides a simplified way of splitting a string by reducing the complexity of regular expression, so instead of using the regex \\r?\\n|\\r we can just make use of \R and it takes care of all the new line characters.

Note: the fact that R is of capital case, java 8 is able to achieve this.

Let’s see it in action below.

Output:

[First Line, Second Line]

Using String’s lines() method [java 11]

Java 11 has introduced new method lines() in String class. It returns stream of lines extracted from the string, splitted by line terminators.

Output:

[First Line, Second Line, Third Line]

Since this method returns a stream, so it opens up lot of options to enable you writing concise and declarative style code.

Using guava library

You can use guava library Splitter class with multiple options such as trimResults() and omitEmptyStrings() to split string by new line in java.
Here is the dependency which you need to add for guava in pom.xml.

Output:

[First Line, Second Line, Third Line]

That’s all about how to split String by newline in java.

Related Posts

  • 13 July

    Remove substring from String in Java

    Table of ContentsUsing String’s replace method to remove substring from String in JavaUsing String’s replaceFirst method to remove substring from String in JavaUsing String’s replaceAll method to remove substring from String in JavaUsing StringBuilder’s delete() method to remove substring from String in JavaUsing StringBuilder’s replace() method to remove substring from String in JavaConclusion In this […]

  • Java String contains IgnoreCase
    23 June

    Java String contains Ignore Case

    Table of ContentsUsing String.toLowerCase()Using Pattern.compile()Using String’s MatchesUsing StringUtils.containsIgnoreCase()Complete program for Java String contains IgnoreCaseConclusion We often have to check if a string contains a substring or not in a case-insensitive manner. There are multiple ways to do so. In this article, we will take a look at these methods for java String contains Ignore Case […]

  • Find and count occurences of substring in String in Java
    02 June

    Find and count occurrences of substring in string in java

    Table of ContentsUsing the indexOf() methodUsing regular expressionUsing split() methodUsing the countMatches() method from Apache Commons library In this post, we will see how to find and count occurrences of substring in string in java. Using the indexOf() method The indexOf() method in java is a specialized function to find the index of the first […]

  • Print double quotes in java
    23 May

    Print double quotes in java

    Table of ContentsPrint double quotes in java using backslash characterPrint double quotes in java using unicode characterPrint double quotes in java by appending double quote character 💡 Outline You can print double quotes in java by escape double quotes using backslash character(\). [crayon-616fe5313c321061667290/] When you print on console using System.out.println, you use double quotes and […]

  • Java Split String by Space
    13 May

    Java split string by space

    Learn about how to split String in java in different ways.

  • 15 April

    How to declare a String array in java

    Learn about how to declare String array in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.