Split without limits split the entire string but if you set a limit it splits up to that limit by the left. How can I do the same by the right?
"a.b.c".split("[.]", 2); // returns ["a", "b.c"]
I would want
"a.b.c".splitRight("[.]", 2); // to return ["a.b", "c"]
EDIT: I want a general solution that works just like splited but reversed so I add a more complex example
I would want
"a(->)b(->)c(->)d".splitRight("\\(->\\)", 3); // to return ["a(->)b", "c", "d"]
You may use look-ahead match:
"a.b.c".split("[.](?=[^.]*$)")
Here you say "I want to split by only that dot which has no other dots after it".
If you want to split by last N dots, you can generalize this solution in this (even more ugly way):
"dfsga.sdgdsb.dsgc.dsgsdfg.dsdg.sdfg.sdf".split("[.](?=([^.]*[.]){0,3}[^.]*$)");
Replace 3
with N-2
.
However I would write a short static method instead:
public static String[] splitAtLastDot(String s) {
int pos = s.lastIndexOf('.');
if(pos == -1)
return new String[] {s};
return new String[] {s.substring(0, pos), s.substring(pos+1)};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With