我有一个字符串,例如,字符串中包含 ${variable1}
和 ${variable2}
。
"select * from table where product ='${variable1}' and name='${variable2}'"
我可以在运行时间内使用eval。
export variable1="iphone"
export variable2="apple"
sql_query=`eval echo ${sql_query}`
然后转动select * from table where product='iphone' and name='apple'
如何在Scala中实现相同的目标?目前,我正在使用字符串替换函数。
还有其他方法吗?Scala中是否有评估?
可以完成,但是您必须挖掘字符串插值细节。
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
从您的评论来看,您是新手编写代码的新手。您还没有很好地描述您的情况和要求。也许是由于缺乏书面英语的经验。
我猜想您想用当前壳环境中的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
您正在描述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'