Java string split with limit and lookahead
In java you can do special string splits as:
- using a limit to define how many occurrences should be split
- positive lookahead - keeping the separator at the left side of the split
- negative lookahead - keeping the separator at the other side of the split
More about regex and strings in java:
Java string split first occurrences
String someStr = "asda-vva-sdwe-wer-333";
String[] limits = someStr.split("-", 2);
String limit1 = limits[0]; // asda
String limit2 = limits[1]; // vva-sdwe-wer-333
for (String limit : limits) System.out.println(limit);
limits = someStr.split("-", 3);
for (String limit : limits) System.out.println(limit);
result:
asda
vva-sdwe-wer-333
asda
vva
sdwe-wer-333
Java string negative lookahead
If you want to split string keeping the separaotor in the new strings on the right side of the split:
String someStr = "asda-vva-sdwe-wer-333";
String[] positive = someStr.split("(?=-)");
String pos1 = positive[1]; // -vva
for (String pos : positive) System.out.println(pos);
result:
asda
-vva
-sdwe
-wer
-333
Java string positive lookahead
If you want to split string keeping the separator in the new strings on the left side of the split.
String someStr = "asda-vva-sdwe-wer-333";
String[] negative = someStr.split("(?<=-)");
String neg1 = negative[1]; // vva-
for (String neg : negative) System.out.println(neg);
result:
asda-
vva-
sdwe-
wer-
333