JavaDevNotes.com

Java String Split Newline Examples

It is common that we wish to Split a Java String using new line as delimiter. This usually happens when we load the contents of a text document to a String and we wish to break it line by line.

Split New Line

In *Nix environment, lines are just separated by the character "\n". In Windows however, the separator is "\r\n". To combine the logic for both scenario, the correct regular expression to denote line feeds for both platform is "\r?\n". This means that "\r" is optional while "\n" is required.

*Nix line feed Example

Here is an example code assuming *Nix environment.

public class TestConsole {
   public static void main(String[] args) {
      String nixSampleLine = "Line 1 \n Line 2 \n Line 3";
      String[] lines = nixSampleLine.split("\\r?\\n");
      for (String line : lines) {
         System.out.println(line);
      }
   }
}

Here is the output:
Line 1 
 Line 2 
 Line 3
Notice the output lines are not trimmed.

Windows line feed Example

Here is an example code assuming Windows environment.

public class TestConsole {
   public static void main(String[] args) {
      String winSampleLine = "Line 1 \r\n Line 2 \r\n Line 3";
      String[] lines = winSampleLine.split("\\r?\\n");
      for (String line : lines) {
         System.out.println(line);
      }
   }
}

Here is the output:
Line 1 
 Line 2 
 Line 3
Notice the output lines are not trimmed.

Split New Line with Trim()

Here is an example of Splitting a string using new line but also trimming each element.

public class TestConsole {
   public static void main(String[] args) {
      String winSampleLine = "Line 1 \r\n Line 2 \r\n Line 3";
      String[] lines = winSampleLine.split("\\s*\\r?\\n\\s*");
      for (String line : lines) {
         System.out.println(line);
      }
   }
}

As you could see, I modified the regular expression ( \r?\n) . I added a sequence of zero or more white space (\s*) both on the left and on the right.

Here is the output.

Line 1
Line 2
Line 3

String Tutorials And Examples