我正在尝试使用Scala读取一个充满查询的sql文件,但是,我正在努力解析包含不是终结符的分号的特殊情况。例如,如果查询是:
SELECT * FROM table WHERE name LIKE "%;%",
它将它分成两个语句,即使它应该是一个。
答案 0 :(得分:0)
答案 1 :(得分:0)
假设查询终结符在一行的末尾始终是;
,我们可以很好地利用
.split(";\\s*\\n");
零个或多个空白字符的 ;
后跟换行符。
或.split("(?m);\\s*$")
使用内联(?m)
多线修饰符,可让我们将该行的末尾与$
匹配。
示例代码:
val a = """SELECT * FROM table WHERE name LIKE "%;%"
AND regexp_replace(
'abcd1234df-TEXT_I-WANT' -- use your input column here instead
, '^[a-z0-9]{10}-(.*)\$' -- matches whole string, captures "TEXT_I-WANT" in \$1
, '\$1' -- inserts \$1 to returnÖ TEXT_I-WANT
) = 'TEXT_I-WANT'
;
SELECT * FROM table WHERE name LIKE "%;%"
AND regexp_replace(
'abcd1234df-TEXT_I-WANT' -- use your input column here instead
, '^[a-z0-9]{10}-(.*)\$' -- matches whole string, captures "TEXT_I-WANT" in \$1
, '\$1' -- inserts \$1 to returnÖ TEXT_I-WANT
) = 'TEXT_I-WANT'
;""".split(";\\s*\\n")
println(a.mkString("Next Query:"))
"(?m)^[\\s\\S]*?;$"
\s
)完整样本:
import scala.util.matching.Regex
object Demo {
def main(args: Array[String]) {
val pattern = new Regex("(?m)^[\\s\\S]*?;\\s*$")
val str = """SELECT * FROM table WHERE name LIKE "%;%"
AND regexp_replace(
'abcd1234df-TEXT_I-WANT' -- use your input column here instead
, '^[a-z0-9]{10}-(.*)\$' -- matches whole string, captures "TEXT_I-WANT" in \$1
, '\$1' -- inserts \$1 to returnÖ TEXT_I-WANT
) = 'TEXT_I-WANT'
;
SELECT * FROM table WHERE name LIKE "%;%"
AND regexp_replace(
'abcd1234df-TEXT_I-WANT' -- use your input column here instead
, '^[a-z0-9]{10}-(.*)\$' -- matches whole string, captures "TEXT_I-WANT" in \$1
, '\$1' -- inserts \$1 to returnÖ TEXT_I-WANT
) = 'TEXT_I-WANT'
;"""
println((pattern findAllIn str).mkString("\n----------------\n"))
}
}