Idiomatic way to split string to an array by last delimiter existence in every occurrence

Viewed 63

Let say I want to split string by ,, e.g

Input string-

"hello world,,,hello country,,hello city"

Expected Output array-

["hello world,", "hello country", "hello city"]

If I use input.split(",,")

Result-

["hello world", ",hello country", "hello city"]

In the above result the extra comma becomes the part of second string, but I would like it to be the part of first string as shown in expected output.

so technically I want while splitting string like ",,," the first comma should be the part of first string rather than last comma being the part of second string. How can I achieve this it in most simple and idiomatic way.

1 Answers

You can use a regex in split, that correspond to: ",, not followed by another ,".

    String s = "hello world,,,hello country,,hello city";
    String[] res = s.split(",,(?!,)");
    System.out.println(Arrays.toString(res)); //[hello world,, hello country, hello city]

xxx(?!,) is a negative-lookahead which match only if , doesn't appear immediately after the xxx.

Related