1

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. E.g. 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

1
  • With your input and your split, I get 4 items, as expected: {"This is my string", "", "This is a new paragraph", "This is another line"}. Commented Oct 30, 2013 at 20:21

4 Answers 4

3

I would use regex:

raw.split("[\\r\\n]+");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but this still doesn't fix my problem, the string is still being lost and I do want to keep blank lines.
please, post more string (not 3 rows) and expected output
2

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.

Comments

0

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]+)

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.