Search code examples
javaregexstringsplit

Java String split by empty lines including empty lines at the end


I have seen many questions and answers online, but it seems that I cannot find the case that I have.

String s = "a\nb\n\nc\n\n\n\n";
String[] split = s.split("\\R");
//is the same as this
String[] splitResult = {"a", "b", "", "c"};

But I would like the result to include array items that are at the end, where only new lines are. Something like this:

String[] s = {"a", "b", "", "c", "", "", "", ""};

Is this possible with any built in method or with the regex? Thanks!


Solution

  • You will have to use the two argument split() method of the String class. While you did mention that it limits the number of results, you overlooked the following:

    limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.

    limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.

    limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.

    I tested the following:

    public static void main(String[] args) {
        String s = "a\nb\n\nc\n\n\n\n";
        String[] split = s.split("\\R", -1);
        System.out.println(Arrays.toString(split));
    }
    

    Giving me the output:

    [a, b, , c, , , , ]