简体   繁体   中英

Java String split() loses string

I have a String called raw . I am trying to split it into an array like so:

lines = raw.split("\\\\r?\\\\n|\\\\r");

This works well for the first few occurrences but then it breaks and totally loses the rest of the string. Eg raw is This is my string\\n\\nThis is a new paragraph\\nThis is another line and becomes {"This is my string", "", "This is a new paragraph"} . Is this a bug within Java or am I doing something wrong? How can I fix it?

Edit: I do want to keep blank lines. [\\\\n\\\\r]+ does not keep blank lines

我会使用正则表达式:

raw.split("[\\r\\n]+");

Your code works as expected:

class Test {
    public static void main(String[] args) {
        String raw = "This is my string\n\nThis is a new paragraph\nThis is another line";
        String[] lines = raw.split("\\r?\\n|\\r");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

This prints:

This is my string

This is a new paragraph
This is another line

It is therefore likely that the problem is with how you examine/display the result of split() , not with the split() itself.

You could clean up that regex liek this:

[\\n\\r]+

the + means it will look for whitespace as far as it can before splitting

chances are there's a big in how you're trying to view the answer or something else, I could help you more if you show some code.

if you want to keep the spaces , try

(?=[\\n\\r]+)

You could use the "multi line" flag and simply split on end-of-line:

lines = raw.split("(?m)$\\s*");

The term \\s* consumes the newline characters.


Here's some test code:

String raw  = "This is my string\n\nThis is a new paragraph\nThis is another line";
String[] lines = raw.split("(?m)$\\s*");
System.out.println(Arrays.toString( lines));

Output:

[This is my string, This is a new paragraph, This is another line]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM