0

I have a record like below.

1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,"Sql, Xyz",Abc,Abc,

I wanted to split the string by "," comma separator but I want Sql,Xyz as a single string not two different string like "Sql adn Xyz". So can someone please help me here. Thanks in advance.

z_1_p
  • 409
  • 1
  • 3
  • 16
  • 2
    You can try using CSV-parsing libraries that handle this and more, e.g. https://github.com/tototoshi/scala-csv – Tzach Zohar Jun 07 '18 at 18:27

2 Answers2

1

This might work for you.

def mySplit(str: String): List[String] = {
  var elems = List[String]()

  // break down by quotes first
  val quotes = str.split("\"")
  for(i <- 0 to quotes.length - 1) {

    if(i % 2 == 0) {
      // break down by commas second
      val subelems = quotes(i).split(",")
      for(j <- 0 to subelems.length - 1) {
        if(!subelems(j).isEmpty)
          elems = elems :+ subelems(j)
          // ignore empty elements
      }

    } else {
      // save "whole strings" and
      // don't break into commas
      elems = elems :+ quotes(i)
    }
  }

  return elems
}

Use it like so:

// quick test
val str = "1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,\"Sql, Xyz\",Abc,Abc"
val list = mySplit(str)

Here is the scalafiddle.io

amdelamar
  • 346
  • 3
  • 16
0

I have done, by using regex like below

val str= "1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,\"Sql, Xyz\",Abc,Abc"
val list=str.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)")

list.foreach( x => println(x))
z_1_p
  • 409
  • 1
  • 3
  • 16