Marquinio Marquinio - 1 month ago 4
Java Question

String split not returning empty results

I'm trying to use

"value1:value2::value3".split(":");


Problem is that I want it to include the blank results.

It returns:
[value1, value2, value3]


It should be:
[value1, value2, , value3]


Does anyone know the regexp to fix this?

Ok I found cause of problem. I'm actually reading a text file and it contains this line:

123:;~\&:ST02:M:test:M:4540145::type;12:51253:D:2.2:567766::AL:::::::2.2b


When I process this line reading the text file it produces the erroneous result mentioned above, which is it doesn't include any empty results in cases like this: :::::.

But when I use the above line in a test program it doesn't compile and I get a "invalid escape sequence". I think its because of the "\&".

Is there a workaround to this problem by using a regular expression?

Answer

split does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1).

Comments