Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the same results with Java split as with Python split [duplicate]

Tags:

java

python

regex

In Java:

String base = "a|a||";
String[] stri= .split("\\|");

produces a string array with length 2.

On the other hand in python:

base = "a|a||"
base.split("|")

produces an array with length 4. What do I have to do to get the same result in Java?

like image 342
Christian Avatar asked Nov 28 '25 13:11

Christian


1 Answers

Use split with limit set to negative value:

String base = "a|a||";
String[] stri= .split("\\|", -1);

From the docs (the number at the and is n):

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

like image 169
Krzysztof Krasoń Avatar answered Nov 30 '25 03:11

Krzysztof Krasoń