[Solved] How to split a string at the n’th occurrence of a specific separator in Java [closed]


You can do something like this:

Pattern pat = Pattern.compile("((?:[^\u0003]*\u0003){30}[^\u0003]*)\u0003(.*)");
Matcher matcher = pat.matcher(input);
if (matcher.matches()) {
    String leftPart = matcher.group(1);
    String rightPart = matcher.group(2);
}

The pattern works as follows: The first capture group finds a substring with exactly 30 occurrences of the separator \u0003; the subpattern that finds a substring with no separators, followed by one separator, is repeated 30 times, and this is then followed by another substring with no separators. This must be followed by a separator (the 31st separator), and the second capture group contains everything that’s left in the string. (Note that a parenthesized subpattern that starts with (?: is a non-capture group and does not count in the numbering used by the group() method.)

An alternative is to use the split() method. However, this will require you to reconstruct the left part yourself, by concatenating the first 31 elements of the resulting array (checking first to see if there are actually that many elements), and inserting the separators. Unfortunately, since you’re on Android, you can’t use the String.join() method to help with this, since this was added in Java 8 and Android is still stuck somewhere between Java 6 and Java 7.

Note: I’ve tested this and it works as expected.

1

solved How to split a string at the n’th occurrence of a specific separator in Java [closed]