规模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"))
因此,它会失败。但是,有什么办法,我可以优雅地处理这个?
您可以使用replaceAllIn
的版本,需要一个功能:
"(Bad|Good)".r.replaceAllIn(content, m =>
s"""<font color="${fontColorMap(m.matched)}">${m.matched}</font>"""
)
其中m
是类型scala.util.matching.Regex.Match
的。
似乎没有成为一个版本replaceFirstIn
的,虽然做同样的事情。
似乎是由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?