Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a string with a limit starting by the right in java?

Tags:

java

regex

split

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"]
like image 862
aalku Avatar asked Nov 05 '15 11:11

aalku


1 Answers

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)};
}
like image 91
Tagir Valeev Avatar answered Oct 13 '22 14:10

Tagir Valeev