Home » Java » Split Java String by New Line

Split Java String by New Line

Posted by: admin November 2, 2017 Leave a comment

Questions:

I’m trying to split text in a JTextArea using a regex to split the String by \n However, this does not work and I also tried by \r\n|\r|n and many other combination of regexes.
Code:

public void insertUpdate(DocumentEvent e) {
    String split[], docStr = null;
    Document textAreaDoc = (Document)e.getDocument();

    try {
        docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
    } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    split = docStr.split("\n");
}
Answers:

This should cover you:

String lines[] = string.split("\r?\n");

There’s only really two newlines (UNIX and Windows) that you need to worry about.

Questions:
Answers:

If you don’t want empty lines:

String.split("[\r\n]+")

Questions:
Answers:

split method is using regex (regular expressions). Since Java 8 regex supports \R which represents (from documentation of Pattern class):

Linebreak matcher
\R         Any Unicode linebreak sequence, is equivalent to
\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

So we can use it to match:

As you see \r\n is placed at start of regex which ensures that regex will try to first match this pair, and only if it fails it will try to match single character line separators.


So if you want to split on line separator use split("\\R").

If you don’t want to remove from resulting array trailing empty strings "" use split(regex, limit) with negative limit parameter like split("\\R", -1).

If you want to treat one or more continues empty lines as single delimiter use split("\\R+").

Questions:
Answers:
String.split(System.getProperty("line.separator"));

This should be system independent

Questions:
Answers:

You don’t have to double escape characters in character groups.

For all non empty lines use:

String.split("[\r\n]+")

Questions:
Answers:

Maybe this would work:

Remove the double backslashes from the parameter of the split method:

split = docStr.split("\n");

Questions:
Answers:

The above code doesnt actually do anything visible – it just calcualtes then dumps the calculation. Is it the code you used, or just an example for this question?

try doing textAreaDoc.insertString(int, String, AttributeSet) at the end?

Questions:
Answers:

For preserving empty lines from getting squashed use:

String lines[] = String.split("\r?\n", -1);

Questions:
Answers:

All answers given here actually do not respect Javas definition of new lines as given in e.g. BufferedReader#readline. Java is accepting \n, \r and \r\n as new line. Some of the answers match multiple empty lines or malformed files. E..g. <sometext>\n\r\n<someothertext> when using [\r\n]+would result in two lines.

String lines[] = string.split("(\r\n|\r|\n)", -1);

In contrast, the answer above has the following properties:

  • it complies with Javas definition of a new line such as e.g. the BufferedReader is using it
  • it does not match multiple new lines
  • it does not remove trailing empty lines
Questions:
Answers:

String lines[] =String.split( System.lineSeparator())

Questions:
Answers:

After failed attempts on the basis of all given solutions. I replace \n with some special word and then split. For me following did the trick:

article = "Alice phoned\n bob.";
article = article.replace("\n", " NEWLINE ");
String sen [] = article.split(" NEWLINE ");

I couldn’t replicate the example given in the question. But, I guess this logic can be applied.

Questions:
Answers:

As an alternative to the previous answers, guava’s Splitter API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :

import com.google.common.base.Splitter;

Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);

Note that the result is an Iterable and not an array.

Questions:
Answers:
  • try this hope it was helpful for you

 String split[], docStr = null;
Document textAreaDoc = (Document)e.getDocument();

try {
    docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
} catch (BadLocationException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

split = docStr.split("\n");

Questions:
Answers:
package in.javadomain;

public class JavaSplit {

    public static void main(String[] args) {
        String input = "chennai\nvellore\ncoimbatore\nbangalore\narcot";
        System.out.println("Before split:\n");
        System.out.println(input);

        String[] inputSplitNewLine = input.split("\n");
        System.out.println("\n After split:\n");
        for(int i=0; i<inputSplitNewLine.length; i++){
            System.out.println(inputSplitNewLine[i]);
        }
    }

}