With some matching as e.g described here: How to pattern match using regular expression in Scala? the code for this could look like the below, assuming your initial expression is passed in as sequence of lines (note that JSONObject as used below is deprecated, so replace this with some alternative).
object Parser {
implicit class Regex(sc: StringContext) {
def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}
def toJson(tablename: String, columns: Seq[(String,String)]): String = {
val columnList: List[JSONObject] = columns.toStream.map(x => JSONObject(Map("columnname" -> x._1, "datatype" -> x._2))).toList
JSONArray(List(JSONObject(Map("tableName" -> tablename, "columns" -> JSONArray(columnList))))).toString()
}
def parse(lines: Seq[String]): (String, Seq[(String,String)]) = {
lines.mkString("").toLowerCase match {
case r"create\s+table\s+(\S+)${tablename}\s+\((.+)${columns}\).*" =>
val columnWithType: immutable.Seq[(String, String)] = columns.split(",").toStream
.map(x => x.split("\\s+"))
.map(x => (x.head.toLowerCase, x(1).toLowerCase))
(tablename, columnWithType)
case _ => ("",Seq.empty)
}
}
}
To test that with your test string:
val data: (String, Seq[(String, String)]) = Parser.parse(Seq("CREATE TABLE TEMP (", "ID INT,", "NAME STRING)"))
println(Parser.toJson(data._1, data._2))