Regex to split a string when there is nothing between two occurrences of a separator

Suppose I want to break this line a^b^c^d^e^^^f^g^h^^^, I just do string.split("\\^")that which returns me an array of 10 ie length [a, b, c, d, e, , , f, g, h]. However, I need an array of length 13 that accepts separator occurrences after h.

I can do something like this to achieve what I want

    string = string.replace("^", "^ ");
    String[] split = string.split("\\^");

    for(String x : split){
        System.out.println(x.trim());
    }

but it seems overloaded. Is there a regex for this?

+4
source share
1 answer

You can do it

String[] split = string.split("\\^", -1);

and it will not drop trailing delimiters.


If you really want to trim the last delimiter to get 12 values, you can do

String[] split = string.replaceAll("\\^$", "").split("\\^", -1);

, 12. , ( null )

String[] split = Arrays.copyOf(string.split("\\^", -1), 12);
+4

All Articles