Java regex program to split a string with line endings as delimiter

JavaObject Oriented ProgrammingProgramming

In windows "\r\n" acts as the line separator. The regular expression "\\r?\\n" matches the line endings.

The split() method of the String class accepts a value representing a regular expression and splits the current string into array of tokens (words), treating the string between the occurrence of two matches as one token.

Therefore, if you want to split a string with line endings as delimiter, invoke the split() method on the input string by passing the above specified regular expression as a parameter.

Example

 Live Demo

import java.util.Scanner;
public class RegexExample {
   public static void main(String[] args) {
      System.out.println("Enter your input string: ");
      Scanner sc = new Scanner(System.in);
      String input = " sample text \r\n line1 \r\n line2 \r\n line3 \r\n line4";
      String[] strArray = input.split("\\r?\\n");
      for (int i=0; i<strArray.length; i++) {
         System.out.println(strArray[i]);
      }
   }
}

Output

Enter your input string:
sample text
line1
line2
line3
line4
raja
Published on 10-Jan-2020 11:55:28
Advertisements