Reputation: 1340
In java doc of public String\[\] split(String regex)
we can find example:
The string
"boo:and:foo"
, for example, yields the following results with these expressionsRegex Result
o
{ "b", "", ":and:f" }
What is the second result ""
come from? From between b
and oo
, or oo
and :and:f
?
Upvotes: 0
Views: 233
Reputation: 627087
Note that for a regex engine, locations between characters also count. So, the regex engine sees the boo:and:foo
string as
<EMPTY>b<EMPTY>o<EMPTY>o<EMPTY>:<EMPTY>a<EMPTY>n<EMPTY>d<EMPTY>:<EMPTY>f<EMPTY>o<EMPTY>o<EMPTY>
^between^ ^between^
As the first ^between^
is not at the end of the string, split
keeps the empty location (string) in the results. The trailing empty elements are removed as the end since the int limit
argument is 0
by default. If you pass -1
(a non-positive value), all the trailing empty elements will be present in the resulting array. See String#split reference.
Upvotes: 1
Reputation: 2326
When you use the delimiter o
and there are two delimiters next to eachother, it yields an empty string. So for instance if you have a String foo::bar
and split it with :
you will get {"foo", "", "bar"}
because the space between ::
is treated as an empty string when splitting.
If you would like to split without having any empty strings, take a look at this question.
Ending empty strings?
When split is given zero or no limit argument it discards trailing empty fields
Ref: Java: String split(): I want it to include the empty strings at the end
Upvotes: 4