Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala replace an String with a List of Key/Values

Tags:

scala

I have different Strings like this

" Hello *|USERNAME|*,

  to activate your account please click here *|ACTIVATION_LINK|*
"

another example

" Hello,

  to reset your password please click here *|RESET_URL|*
"

for the first String I would have a List of key values like this

((USERNAME, Nick),(ACTIVATION_URL, http://whateverhost/activation_url))

for the second

((RESET_URL, http://whateverhost/reset_url))

I want to replace the strings with the List of Key/Values, the List can have a variable length and the occurrences of the keys in the String may be multiple

I tried something like this

mapKeyValues.map { x => bodyString.replaceAll(x._1, x._2) }

But the problem is I get a new List where each row has the replacement of one row of the Key/Values

Is there a way to do this?

like image 765
agusgambina Avatar asked Sep 16 '25 06:09

agusgambina


1 Answers

You can do it using foldLeft:

mapKeyValues
  .foldLeft (bodyString) {case (acc,(key,value))=>acc.replaceAll(key, value)}
like image 193
Nyavro Avatar answered Sep 19 '25 12:09

Nyavro