blunderboy blunderboy - 5 months ago 20
Scala Question

Difference between splitting a string with character and string in scala

I am splitting a string based on a pipe

character in scala. I see two different options to do this. I am surprised to see I got two different results in different scenarios.

Check this out:

enter image description here

In case of string, it also returned pipe character while in case of character it returned the results as expected.

I am curious to know the difference in both of these.


The thing is when you are proving the parameter as String this String can be a regular expression. And | is a special character in the world of regular expressions.

This will become more clear to you after following example,

scala> val s1 = "abcdef"
s1: String = abcdef

scala> s1.split("|")
res7: Array[String] = Array(a, b, c, d, e, f)

If you want to get the desired result you will have to escape | using \\

scala> val s1 = "abcdef"
s1: String = abcdef

scala> s1.split("\\|")
res7: Array[String] = Array(abcdef)