How to split a line with a limit starting on the right in java?

Splitting without limits splits the entire line, but if you set a limit, it splits to this limit on the left. How can I do the same rightfully?

"abc".split("[.]", 2); // returns ["a", "bc"] 

I would like

 "abc".splitRight("[.]", 2); // to return ["ab", "c"] 

EDIT: I want the general solution to work the same way as split, but be reversed, so I'm adding a more complex example

I would like

 "a(->)b(->)c(->)d".splitRight("\\(->\\)", 3); // to return ["a(->)b", "c", "d"] 
+5
source share
3 answers

I would try something like this:

 public List<String> splitRight(String string, String regex, int limit) { List<String> result = new ArrayList<String>(); String[] temp = new String[0]; for(int i = 1; i < limit; i++) { if(string.matches(".*"+regex+".*")) { temp = string.split(modifyRegex(regex)); result.add(temp[1]); string = temp[0]; } } if(temp.length>0) { result.add(temp[0]); } Collections.reverse(result); return result; } public String modifyRegex(String regex){ return regex + "(?!.*" + regex + ".*$)"; } 

The regex for split is wrapped differently, so for \\. you will receive: \\.(?!.*\\..*$) to match and divide by the last delimiter. The string is split several times using this regular expression, the second element of the result array is added to the list, the next bifurcation is performed on the first element of the result array.

The effect of the above method on the line of your example is as expected.

+1
source

You can use leading match:

 "abc".split("[.](?=[^.]*$)") 

Here you say: "I want to divide only that point that has no other points after it."

If you want to divide by the last N points, you can generalize this solution to this (even more ugly):

 "dfsga.sdgdsb.dsgc.dsgsdfg.dsdg.sdfg.sdf".split("[.](?=([^.]*[.]){0,3}[^.]*$)"); 

Replace 3 with N-2 .

However, instead, I would write a short static method:

 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)}; } 
+5
source

Despite the fact that you said that the reverse will take a lot of time, here is a small program that reads String and splits it into a limit;

 static String[] leftSplit(String input, String regex, int limit) { String reveresedInput = new StringBuilder(input).reverse().toString(); String[] output = reveresedInput.split(regex, limit); String tempOutput[] = new String[output.length]; for(int i = 0;i<output.length;++i) { tempOutput[tempOutput.length-i-1] = new StringBuilder(output[i]).reverse().toString(); } return tempOutput; } public static void main(String[] args) { System.out.println(Arrays.toString(leftSplit("abc", "[.]", 2))); System.out.println(Arrays.toString(leftSplit("I want to. Split this. by the. right side", "[.]", 2))); } 
+2
source

Source: https://habr.com/ru/post/1235292/


All Articles