我试图在JTextArea中使用正则表达式分割文本,通过\n分割字符串,然而,这并不奏效,我也尝试了\r\n|\r|n和许多其他正则表达式组合。 代码:

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

当前回答

也许这样可以:

从split方法的参数中移除双反斜杠:

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

其他回答

你不必在字符组中使用双转义字符。

对于所有非空行使用:

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

上述答案在Android上对我没有帮助,多亏了Pshemo的回应,我在Android上很管用。我将在这里留下一些Pshemo的回答:

split("\\\\n")

String lines[] =字符串。split (System.lineSeparator ())

如果出于某种原因,您不想使用String。split(例如,因为正则表达式),并且你想在Java 8或更新版本上使用函数式编程:

List<String> lines = new BufferedReader(new StringReader(string))
        .lines()
        .collect(Collectors.toList());

这里给出的所有答案实际上都不尊重java对新行的定义,例如BufferedReader#readline。Java接受\n, \r和\r\n作为新行。一些答案匹配多个空行或格式错误的文件。E . g。当使用[\r\n]+时,<someothertext> \n\r\n<someothertext>将导致两行。

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

相比之下,上面的答案具有以下性质:

它符合java对新行的定义,例如BufferedReader正在使用它 它不匹配多个新行 它不移除尾随的空行