Tuesday, 15 August 2017

How to Split String by New Line in JAVA

How to Split String by New Line
Review the following new line in different operating system.

\n Unix, New Mac
\r Old Mac
\r\n Windows and DOS
In a nutshell, you can match the new line with this regex \r?\n
Split example

Java regex \r?\n example to split a String by new line.

SplitByNewLineExample.java


package com.mkyong;

public class SplitByNewLineExample {

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder("");
        sb.append("   aaa \n");
        sb.append("     bbb          \n");
        sb.append("ccc  \n");
        sb.append("\n");
        sb.append("ddd\r\n");
        sb.append("\r\n");
        sb.append("eee\n");

        String text = sb.toString();
        System.out.println("---Original---");
        System.out.println(text);

        System.out.println("---Split---");
        int count = 1;
        String[] lines = text.split("\\r?\\n");
        for (String line : lines) {
            System.out.println("line " + count++ + " : " + line);
        }

    }
}

Output
---Original---
   aaa
     bbb
ccc

ddd

eee

---Split---
line 1 :    aaa
line 2 :      bbb
line 3 : ccc
line 4 :
line 5 : ddd
line 6 :
line 7 : eee

Post a Comment

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search