使用字符串插值字符串替换斯卡拉

问题描述 投票:0回答:2

规模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>""")

我想用正则表达式替换字符串。在这种情况下$$ 1可以获取匹配的字符串,但我不知道怎么做,在$ {}。

加。我知道,斯卡拉将插值转化为这样的事情

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

因此,它会失败。但是,有什么办法,我可以优雅地处理这个?

string scala string-interpolation
2个回答
1
投票

您可以使用replaceAllIn的版本,需要一个功能:

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

其中m是类型scala.util.matching.Regex.Match的。

似乎没有成为一个版本replaceFirstIn的,虽然做同样的事情。


0
投票

似乎是由regex group variable插补scala StringContext插值引起了不同的插值order.And StringContext需要评估之前,首先去的regex插值。也许我们可以尝试regex replace interpolation前首先获得价值,如:

"(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?
© www.soinside.com 2019 - 2024. All rights reserved.