Scala 用键/值列表替换字符串 [英] Scala replace an String with a List of Key/Values
本文介绍了Scala 用键/值列表替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的不同字符串
" Hello *|USERNAME|*,
to activate your account please click here *|ACTIVATION_LINK|*
"
另一个例子
" 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))
第二个
((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
我试过这样的事情
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?
推荐答案
你可以使用 foldLeft:
You can do it using foldLeft:
mapKeyValues
.foldLeft (bodyString) {case (acc,(key,value))=>acc.replaceAll(key, value)}
这篇关于Scala 用键/值列表替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文