替换字符串

时间:2016-05-11 12:08:02

标签: scala functional-programming

我有一张地图,我在其中存储了要在字符串中替换的key->值对参数。 例如地图(id - > 1,名字 - > peter)& https://example.com/#id/#name应生成此字符串:https://example.com/1/peter

这是我的代码到目前为止,它的工作原理。有没有办法让这项工作没有var

def replaceUrlParams(url: String, params: Map[String, String]): String = {
    var replacement: String = url
    params.map(value => {
        replacement = replacement.replaceAll("#"+value._1, value._2)
    })
    replacement
}

2 个答案:

答案 0 :(得分:12)

您正在寻找foldLeft

 params.foldLeft(url) { case (str, (key, value)) =>
    str.replaceAll("#" + key, value)
 }

答案 1 :(得分:1)

只需使用正则表达式和replaceAllIn

def replaceUrlParams(url: String, params: Map[String, String]): String = {
  val placeholder = raw"#(\w[\w\d]*)".r;
  placeholder.replaceAllIn(url, paramMatch => {
    val key = paramMatch.group(1);
    params(key) // Return the value of params[key] as the replacement.
  });
}