Java’s string split(regex) function splits at all instances of the regex. Python’s partition function only splits at the first instance of the given separator, and returns a tuple of {left,separator,right}.
How do I achieve what partition does in Java?
e.g.
"foo bar hello world".partition(" ")
should become
"foo", " ", "bar hello world"
-
Is there an external library which
provides this utility already? -
how would I achieve it without
an external library? -
And can it be achieved without an external library and without Regex?
NB. I’m not looking for split(” “,2) as it doesn’t return the separator character.
The
String.split(String regex, int limit)is close to what you want. From the documentation:Here’s an example to show these differences (as seen on ideone.com):
A partition that keeps the delimiter
If you need a similar functionality to the partition, and you also want to get the delimiter string that was matched by an arbitrary pattern, you can use
Matcher, then takingsubstringat appropriate indices.Here’s an example (as seen on ideone.com):
The regex
\d+of course is any digit character (\d) repeated one-or-more times (+).