0

scala 2.11.6

val fontColorMap = Map( "Good" -> "#FFA500", "Bad" -> "#0000FF")
val content = "Good or Bad?"
"(Bad|Good)".r.replaceFirstIn(content,s"""<font color="${fontColorMap("$1")}">$$1</font>""")

I want to replace the String using regex. In this case $$1 can fetch the matched string, but I dont know how to do it in ${}.

plus. I know that scala will translate the interpolation into something like this

new StringContext("""<font color=""",""">$$1</font>""").s(fontColorMap("$1"))

Thus it will fail. But, is there any way I can handle this gracefully?

2 Answers 2

1

You can use the version of replaceAllIn that takes a function:

"(Bad|Good)".r.replaceAllIn(content, m => 
  s"""<font color="${fontColorMap(m.matched)}">${m.matched}</font>"""
)

where m is of type scala.util.matching.Regex.Match.

There doesn't seem to be a version of replaceFirstIn that does the same thing though.

Sign up to request clarification or add additional context in comments.

2 Comments

I think that is what OP means.
Yeah, I only want to replace the first one
0

Seems is caused by regex group variable interpolation with scala StringContext interpolation has the different interpolation order.And StringContext need to evaluate firstly before go to the regex interpolation. Maybe we can try to get value firstly before regex replace interpolation, like:

"(Bad|Good)".r.findFirstIn(content).map(key => {
    val value = fontColorMap(key)
    content.replaceFirst(key, s"""<font color="$value">$key</font>""")
 }).get
 > <font color="#FFA500">Good</font> or Bad?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.