I wrote this code
val line = "Aaa Bbb Ccc"
line.split(" ")
which produces the following output as expected:
res31: Array[String] = Array(Aaa, Bbb, Ccc)
I change the code slightly:
val line = "Aaa|Bbb|Ccc"
line.split("|")
And now I don't understand the output:
res30: Array[String] = Array("", A, a, a, |, B, b, b, |, C, c, c)
Why did this happen?
split
takes a string representing the regex to split on - "|" is a regex for the empty string or another empty string, so it splits between every character. You need to escape the |
:
line.split("\\|")
alternatively you can use the overload which takes a Char
parameter to split on (defined in StringOps
):
line.split('|')
Pipe "|" is a regex character that means either of two options. In that case either empty or empty.
Try escaping it to use it as a character:
val line = "Aaa|Bbb|Ccc"
line.split("\\|")
res0: Array[String] = Array(Aaa, Bbb, Ccc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With