Java/scala 正则表达式模式不替换字符串

标签 java regex scala

我的输入如下。

 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/

相关文章:

java - 使用 Java Restful 服务进行身份验证

regex - 正则表达式中 * 运算符的混淆

Python re.sub 使用非贪婪模式 (.*?) 和字符串结尾 ($) 它变得贪婪了!

scala - 如何在本地模式下更改执行程序的数量?

Scala:继承特征中的匿名类型

java - 值未将 selectOneMenu 设置为 ManagedBean

java - 有没有办法让按钮对对象执行操作,而无需创建实现 ActionListener 的新类?

java - Java Annotation 的默认属性

Java正则表达式分割第一行和所有剩余行中的文本

scala - 我如何否定 spark scala 中的 isin 方法