What do you mean by "it's not feasible"? It works just fine:
// s is the same string you provided
s.split(";").map { keyVal =>
val Array(key, value, _*) = keyVal.split("=", 2)
key -> value
}
// result ->
res2: Array[(String, String)] = Array(
("data source", "local/SQL,1433"),
("initial catalog", "Employee"),
("user id", "user_first"),
("password", "abc@123"),
("encrypt", "true"),
("connectretrycount", "3"),
("connection timeout", "30")
)
And easily use this as a udf. Or you might prefer using regular expressions:
val extractorPattern = "data source=([^;]*);initial catalog=([^;]*);.*".r
// expand this for other fields as well
val extractorPattern(dataSource, initialCatalog) = s
// The result in ammonite:
// dataSource: String = "local/SQL,1433"
// initialCatalog: String = "Employee"
There are also some other approaches, you can also take the regex and use it in spark API functions.
Update
If you want to access it as a variable inside the function, you can do it in a safe way:
val dataSource = res2.collectFirst { case ("data source", dataSource) => dataSource }
// dataSource: Option[String] = Some(value = "local/SQL,1433")
Or if you're sure that data source or basically any key always exists in the original string, then:
val Some(dataSource) = res2.collectFirst { case ("data source", dataSource) => dataSource }
// dataSource: String = "local/SQL,1433"