0

"abc|xyz|".split("\\|").foreach(println) ===> only displaying abc and xyx

println("abc|xyz|".split("\\|").length) ===> length should be 3 but is showing as 2.

When I split a string with pipe delimited, and the value of the last column is empty. The split function is ignoring the last value.

Yeti
  • 1,108
  • 19
  • 28

1 Answers1

3

You should be using limit with split function as -1 which will give you as expected

"abc|xyz|".split("\\|", -1).foreach(println)

Which results in output as abc, xyx and ''

println("abc|xyz|".split("\\|", -1).length)

This results in length as 3

koiralo
  • 22,594
  • 6
  • 51
  • 72
  • Perhaps you could explain why this works. From a pure regex split point of view, rightfully nothing _should_ be in the third position, because there is only a boundary marker in between the last pipe and end of string. – Tim Biegeleisen May 07 '18 at 14:42