When I split a String using ,
works as expected :
val line1 = "this,is,a,test" //> line1 : String = this,is,a,test
val sLine = line1.split(",")
however if I use |
the String is split into its character elements and added to array :
val line1 = "this|is|a|test" //> line1 : String = this|is|a|test
val sLine = line1.split("|") //> sLine : Array[String] = Array("", t, h, i, s, |, i, s, |, a, |, t, e, s, t)
Why is this occurring because of | character ?
possible solutions
val sLine2 = line1.split('|')
because '
denotes a character, a single character, split
does not treat it as a regexp
val sLine2 = line1.split("\\|")
to escape the special alternation |
regexp character. This is why it isn't working. split
is treating |
as a zero width regexp and so the string is vapourized into its component characters
As pipe is a special regex character, I believe you need to escape it like so "\\|"
in order for it to work
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