
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Regex Program to Split a String with Line Endings as Delimiter
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
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
Advertisements