我的输入如下。
val source = """ {
"tgtPartitionColumns" : "month_id="${month_id}"",
"splitByCol" : "${splitByCol}"
}"""
val inputArgsMap = Map("splitByCol"->"ID","month_id"->"Jan")
我的正则表达式替换函数如下
import scala.collection.mutable
import java.util.regex.Pattern
def replaceVariablesWithValues(expr: String, argsMap: Map[String, String]): String = {
val regex = "\\$\\{(\\w+)\\}"
val unPassedVariables = new mutable.ListBuffer[String]()
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(expr)
var replacedString: Option[String] = None
while (matcher.find) {
val key = matcher.group(1)
if (argsMap.contains(key)) {
replacedString = Some(expr.replace("${" + key + "}", argsMap(key)))
} else {
unPassedVariables += key
}
}
if (unPassedVariables.nonEmpty)
throw new IllegalStateException(s"No matching key found in input arguments for $unPassedVariables")
replacedString.getOrElse("")
}
它能够将 Month_id 作为一个组进行检测,但不会在源中被替换。
最佳答案
正则表达式实际上很好,你的循环中有一个错误,这可以修复它:
replacedString = Some(replacedString.getOrElse(expr).replace("${" + key + "}", argsMap(key)))
关于Java/scala 正则表达式模式不替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48667986/