- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- How can we split a string by sentence as a delimiter in Java?
- How to split a string with a string delimiter in C#?
- Java regex program to split a string at every space and punctuation.
- Java Program to split a string with dot
- How to split string by a delimiter string in Python?
- Java program to split and join a string
- How to match end of a particular string/line using Java RegEx
- How to match beginning of a particular string/line using Java RegEx
- How do we use a delimiter to split string in Python regular expression?
- Java Program to split a string using Regular Expression
- Write a Python function to split the string based on delimiter and convert to series
- Split string into sentences using regex in PHP
- How do we split a string with any whitespace chars as delimiters using java?
- Python program to split a string and join with comma
- Split String with Dot (.) in Java

Advertisements