Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to split String using |

Tags:

string

scala

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 ?

like image 240
blue-sky Avatar asked Apr 15 '14 13:04

blue-sky


2 Answers

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

like image 129
Vorsprung Avatar answered Oct 09 '22 09:10

Vorsprung


As pipe is a special regex character, I believe you need to escape it like so "\\|" in order for it to work

like image 22
cmbaxter Avatar answered Oct 09 '22 10:10

cmbaxter