首页 > 解决方案 > scala.js 的字符串插值,如 java.text.MessageFormat

问题描述

我需要像java.text.MessageFormatscala.js 这样的字符串插值。具体来说,我需要一些东西来让我为我们的翻译选择打印参数的顺序(如“{0}”、“{1}”)。

我想要的是:

val world = "world"
format("Hello {0}", world)
format("Hello {1}{0}", "!", world) // should print: "Hello world!"

不能使用的:

"Hello $world"  
"Hello %s".format(world)

有什么我可以使用但还没有找到的吗?为了一致性,我肯定更喜欢在我的字符串中使用'{x}'。

编辑:

使用 sjrd 的回答,我想出了以下内容:

/**
* String interpolation [[java.text.MessageFormat]] style:
* {{{
*   format("{1} {0}", "world", "hello") // result: "hello world"
*   format("{0} + {1} = {2}", 1, 2, "three") // result: "1 + 2 = three"
*   format("{0} + {0} = {0}", 0) // throws MissingFormatArgumentException
* }}}
* @return
*/
def format (text: String, args: Any*): String = {
   var scalaStyled = text
   val pattern = """{\d+}""".r
   pattern.findAllIn(text).matchData foreach {
      m => val singleMatch = m.group(0)
           var number = singleMatch.substring(1, singleMatch.length - 1).toInt
           // %0$s is not allowed so we add +1 to all numbers
           number = 1 + number
           scalaStyled = scalaStyled.replace(singleMatch, "%" + number + "$s")
   }
   scalaStyled.format(args:_*)
}

标签: javascriptstringscalascala.jsstring-interpolation

解决方案


您可以使用String.format显式索引:

val world = "world"
"Hello %1$s".format(world)
"Hello %2$s%1$s".format("!", "world")

显式索引在 a 之前指定$。它们是基于 1 的。

它不如. {x}_ {x}_%x$sformat


推荐阅读