prosseek
prosseek

Reputation: 191069

String replacement issue with `replaceAllIn` method in Scala

I have this template formatting code in Scala from Better String formatting in Scala

  def getTemplateString(template:String, replacement:Map[String, String]) = {
    replacement.foldLeft(template)((s:String, x:(String,String)) => ( "#\\{" + x._1 + "\\}" ).r.replaceAllIn( s, x._2 ))
  }

The issue is that with a mapped value with '$' character, I get Illegal group reference java.lang.IllegalArgumentException: Illegal group reference error.

val template = "#{a}"
val map = Map[String, String]("a" -> "$bp")
val res = getTemplateString(template, map)
println(res)

How to fix this issue?

Upvotes: 1

Views: 66

Answers (1)

SCouto
SCouto

Reputation: 7928

Try escaping the $ symbol:

val map = Map[String, String]("a" -> "\\$bp")

Upvotes: 1

Related Questions