Scala-替换字符串中的文本占位符

时间:2018-12-15 04:02:55

标签: string scala parsing replace

让我们说我有一个字符串模板,其中包含N个占位符:

"{placeholder1}/{placeholder2}-{placeholder3}/{placeholder4}.{placeholder5}"

假设我有一张地图:

"placeholder1" -> "aaa", 
"placeholder2" -> "xxx", 
"placeholder3" -> "yyy", 
"placeholder4" -> "zzz", 
"placeholder5" -> "bbb"

鉴于此地图和占位符字符串模板,是否可以将占位符键替换为占位符值?还是需要使用正则表达式?

2 个答案:

答案 0 :(得分:4)

您可以遍历数据并使用String.replace应用于模板,并继续遍历新状态。

给出,

scala> val template = "{placeholder1}/{placeholder2}-{placeholder3}/{placeholder4}.{placeholder5}"
template: String = {placeholder1}/{placeholder2}-{placeholder3}/{placeholder4}.{placeholder5}

scala> val data = Map("placeholder1" -> "aaa", 
                      "placeholder2" -> "xxx", 
                      "placeholder3" -> "yyy", 
                      "placeholder4" -> "zzz", 
                      "placeholder5" -> "bbb")
data: scala.collection.immutable.Map[String,String] = HashMap(placeholder5 -> bbb, placeholder1 -> aaa, placeholder3 -> yyy, placeholder2 -> xxx, placeholder4 -> zzz)

使用foldLeft将模板应用于数据。我假设{}表示模板的占位符。

scala> data.foldLeft(template){ case (newState, kv) => newState.replace(s"{${kv._1}}", kv._2)}
res6: String = aaa/xxx-yyy/zzz.bbb

注意::上面的kvMap中的每个条目,或者,您可以将kv分解为(k, v)

scala> data.foldLeft(template){ case (newState, (k, v)) => newState.replace(s"{$k}", v)}
res7: String = aaa/xxx-yyy/zzz.bbb

Alternative solution

尽管.foldLeft就足够了,但是您可以编写自己的香草递归,该递归一次应用一个条目并保持迭代直到数据为空。

def format(template: String, data: Map[String, String]): String = {
  if(data.isEmpty) template
  else format(template.replace(s"{${data.head._1}}", data.head._2), data.tail)
}

val formatted = format(template, data) // aaa/xxx-yyy/zzz.bbb

答案 1 :(得分:0)

为什么不使用cplusplus.com

def replace(m: Map[String,String]) = s"${m("placeholder1")}/${m("placeholder2")}-...."