在scala中给出没有“(和”)“的表列别名

时间:2017-02-12 07:24:02

标签: regex scala

我有一个表示SQL查询的select子句的字符串,例如:

val a = "eid,year(join_dt),month(join_dt)" 

我想要select $a from emp

我想为字符串中的每个元素赋予别名,输出sting应为"eid as eid, year(join_dt) as yearjoin_dt, month(join_dt) as monthjoin_dt" - 如何执行此字符串操作?

1 个答案:

答案 0 :(得分:1)

不确定它是否真的是一个强大的解决方案(假设输入是一个结构良好的逗号分隔的字段列表,并且字段名称只有字母数字和下划线字符),但这应该这样做:

val a = "eid,year(join_dt),month(join_dt)"

val result = a.split(",")
 .map(s => s"$s as ${s.replaceAll("[^0-9a-zA-Z_]", "")}")
 .mkString(", ")

println(result)
// eid as eid, year(join_dt) as yearjoin_dt, month(join_dt) as monthjoin_dt