Split Java String by New Line

2018-12-31 05:51发布

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");
}

19条回答
妖精总统
2楼-- · 2018-12-31 06:01
  • 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");
查看更多
还给你的自由
3楼-- · 2018-12-31 06:02

If you don’t want empty lines:

String.split("[\\r\\n]+")
查看更多
浪荡孟婆
4楼-- · 2018-12-31 06:04

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.

查看更多
谁念西风独自凉
5楼-- · 2018-12-31 06:07

Maybe this would work:

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

split = docStr.split("\n");
查看更多
无色无味的生活
6楼-- · 2018-12-31 06:08

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.

查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 06:09

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

For all non empty lines use:

String.split("[\r\n]+")
查看更多
登录 后发表回答