Reputation: 53896
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 ?
Upvotes: 5
Views: 147
Reputation:
scala> val line1 = "this,is,a,test"
line1: java.lang.String = this,is,a,test
scala> line1.split(",")
res2: Array[java.lang.String] = Array(this, is, a, test)
scala> var line2 = "this|is|a|test"
line2: java.lang.String = this|is|a|test
scala> line2.split("\\|")
res3: Array[java.lang.String] = Array(this, is, a, test)
Upvotes: 1
Reputation: 34457
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
Upvotes: 4
Reputation: 35463
As pipe is a special regex character, I believe you need to escape it like so "\\|"
in order for it to work
Upvotes: 3