Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split not returning empty results

Tags:

java

string

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?

like image 789
Marquinio Avatar asked Sep 21 '10 21:09

Marquinio


People also ask

Can string split return empty array?

Using split()If the string and separator are both empty strings, an empty array is returned.

What happens if you split an empty string?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Can Java string split return null?

split(CharSequence input, int limit) . The return value comes from a non-null ArrayList on which toArray is called. toArray does not return null: in the event of an empty list you'll get an empty array back. So in the end, no, you don't have to check for null.

Does Split () return a list?

The split() function returns the strings as a list.


1 Answers

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).

like image 139
casablanca Avatar answered Sep 22 '22 01:09

casablanca