bash在scala中评估类似

问题描述 投票:0回答:2

我有一个字符串,例如字符串中包含${variable1}${variable2}

"select * from table where product ='${variable1}' and name='${variable2}'"

我可以使用eval在运行时在bash中评估字符串。

export variable1="iphone"
export variable2="apple"
sql_query=`eval echo ${sql_query}`

然后转动select * from table where product='iphone' and name='apple'

如何在scala中实现相同的功能?目前我正在使用字符串替换功能。

有没有其他方法这样做? scala中有eval吗?

scala
2个回答
0
投票

它可以完成但你必须深入研究字符串插值细节。

val input="select * from table where product='${variable1}' and name='${variable2}'"

val variable1 = "iphone"
val variable2 = "apple"

val sql_query = StringContext(input.split("\\$[^}]+}"): _*).s(variable1,variable2)
//sql_query: String = select * from table where product='iphone' and name='apple'

请注意,要使其工作,您必须事先知道输入字符串中引用了哪些变量和多少变量。


UPDATE

从您的评论来看,很明显您是编写代码的新手。您还没有很好地描述您的情况和要求。也许是由于缺乏书面英语经验。

我猜你想用在当前shell环境中找到的String值替换引用的变量名。

也许这样的事情。

val exampleStr = "blah '${HOME}' blah '${SHELL}' blah '${GLOB}' blah"

val pattern = "\\$\\{([^}]+)}".r

pattern.replaceAllIn(exampleStr, s =>
                     System.getenv.getOrDefault(s.group(1),"unknown"))
//res0: String = blah '/home/me' blah '/bin/bash' blah 'unknown' blah

0
投票

您正在描述Scala中称为“字符串插值”的功能。在Scala字符串上使用s前缀以启用字符串插值。

$ scala
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_151).
Type in expressions for evaluation. Or try :help.

scala> val variable1 = "iphone"
variable1: String = iphone

scala> val variable2 = "apple"
variable2: String = apple

scala> val sql_query = s"select * from table where product ='${variable1}' and name='${variable2}'"
sql_query: String = select * from table where product ='iphone' and name='apple'
© www.soinside.com 2019 - 2024. All rights reserved.