Sorry couldn't think of a better title. I'm new to Scala and I'm trying to parse out variables out of "{}". I want to be able to write regex that returns all variables out of he handle bars like example below. In some cases the sql string would have one "{}" in others it might have multiple.
val sql_str = "select * from {tbl} a left join {tbl2} b on a.id = b.id "
val r = """.*\{(.*)\}.*""".r
val result = sql_str match {
case r(value) => value
case _ => ""
}
For instance if I had the follow string:
select * from {tbl}
the result should be: tbl
for
select * from {tbl} a left join {tbl2} b on a.id = b.id
the result should be: tbl, tbl2
I tried searching for solution but couldn't find one. Thanks for any pointers you can provide.
CodePudding user response:
This is what I came up with. I don't think it's the greatest answer. If someone has an efficient way please share.
var sql_str = "select * from {tbl} a left join {tbl2} b on a.id = b.id"
var words = sql_str.split("\\s ")
var params = Array[String]()
val pattern = """.*\{(.*)\}.*""".r
words foreach(x=> if ((x match {case pattern(value)=> value case _=> ""})!="") params=params: x )
params foreach(x=> print(x))
CodePudding user response:
"""\{(. ?)}""".r
.findAllMatchIn(sql)
.map(_.group(1))
.foreach(println)
Or a bit less efficient, but, perhaps, somewhat simpler:
"""\{. ?}""".r
.findAllIn(sql)
.map(_.tail.init)
.foreach(println)
This assumes, you don't have nested or unbalanced braces, and will not work very well on something like "foo {bar {bam} baz} {zap}}"
.
If you want to handle those cases, regex is probably not the right tool, you'd be better off with a simple recursive function traversing the string while keeping track of the braces.