按新行拆分 Java 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/454908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:50:28  来源:igfitidea点击:

Split Java String by New Line

javaregexsplitnewline

提问by dr.manhattan

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

我试图拆分文本中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");
}

采纳答案by cletus

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.

您只需要担心两个换行符(UNIX 和 Windows)。

回答by Gumbo

If you don't want empty lines:

如果您不想要空行:

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

回答by Chii

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?

尝试在最后做 textAreaDoc.insertString(int, String, AttributeSet) 吗?

回答by Michael

Maybe this would work:

也许这会奏效:

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

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

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

回答by Martin

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

您不必在字符组中将转义字符加倍。

For all non empty lines use:

对于所有非空行,请使用:

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

回答by Shervin Asgari

String.split(System.getProperty("line.separator"));

This should be system independent

这应该是系统独立的

回答by Naveen

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

}

回答by Pshemo

String#split?(String regex)method is using regex (regular expressions). Since Java 8 regex supports \Rwhich represents (from documentation of Pattern class):

String#split?(String regex)方法是使用正则表达式(正则表达式)。由于 Java 8 正则表达式支持\Rwhich 表示(来自Pattern 类的文档):

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

换行匹配器
\R 任何 Unicode 换行序列,等价于 \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

So we can use it to match:

所以我们可以用它来匹配:

As you see \r\nis placed at start of regex which ensures that regex will try to match this pairfirst, and only if that match fails it will try to match single characterline separators.

如您所见,\r\n它位于 regex 的开头,这确保 regex 将首先尝试匹配这一,并且仅当匹配失败时,它才会尝试匹配单字符行分隔符。



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

因此,如果您想在行分隔符上拆分,请使用split("\\R").

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

如果您不想从结果数组中删除尾随空字符串,请""使用split(regex, limit)limit参数,如split("\\R", -1).

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

如果您想将一个或多个连续空行视为单个分隔符,请使用split("\\R+").

回答by husayt

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

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

回答by sevenforce

For preserving empty lines from getting squashed use:

为了防止空行被压扁,请使用:

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