string Scala 中更好的字符串格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4051308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:52:30  来源:igfitidea点击:

Better String formatting in Scala

stringscalaformattingstring-formatting

提问by Debilski

With too many arguments, String.formateasily gets too confusing. Is there a more powerful way to format a String. Like so:

论点太多,String.format很容易变得太混乱。有没有更强大的方法来格式化字符串。像这样:

"This is #{number} string".format("number" -> 1)

Or is this not possible because of type issues (formatwould need to take a Map[String, Any], I assume; don't know if this would make things worse).

或者这是不可能的,因为类型问题(format我假设需要使用 Map[String, Any];不知道这是否会使事情变得更糟)。

Or is the better way doing it like this:

或者是这样做的更好方法:

val number = 1
<plain>This is { number } string</plain> text

even though it pollutes the name space?

即使它污染了名称空间?

Edit:

编辑:

While a simple pimping might do in many cases, I'm also looking for something going in the same direction as Python's format()(See: http://docs.python.org/release/3.1.2/library/string.html#formatstrings)

虽然在许多情况下可能会做一个简单的拉皮条,但我也在寻找与 Python 相同方向的东西format()(参见:http: //docs.python.org/release/3.1.2/library/string.html#formatstrings)

回答by Andrej Herich

In Scala 2.10 you can use string interpolation.

在 Scala 2.10 中,您可以使用字符串插值

val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall")  // James is 1.90 meters tall

回答by Daniel C. Sobral

Well, if your only problem is making the order of the parameters more flexible, this can be easily done:

好吧,如果您唯一的问题是使参数的顺序更灵活,则可以轻松完成:

scala> "%d %d" format (1, 2)
res0: String = 1 2

scala> "%2$d %1$d" format (1, 2)
res1: String = 2 1

And there's also regex replacement with the help of a map:

在地图的帮助下,还有正则表达式替换:

scala> val map = Map("number" -> 1)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map((number,1))

scala> val getGroup = (_: scala.util.matching.Regex.Match) group 1
getGroup: (util.matching.Regex.Match) => String = <function1>

scala> val pf = getGroup andThen map.lift andThen (_ map (_.toString))
pf: (util.matching.Regex.Match) => Option[java.lang.String] = <function1>

scala> val pat = "#\{([^}]*)\}".r
pat: scala.util.matching.Regex = #\{([^}]*)\}

scala> pat replaceSomeIn ("This is #{number} string", pf)
res43: String = This is 1 string

回答by Ruediger Keller

Maybe the Scala-Enhanced-Strings-Plugin can help you. Look here:

也许 Scala-Enhanced-Strings-Plugin 可以帮助你。看这里:

Scala-Enhanced-Strings-Plugin Documentation

Scala 增强型字符串插件文档

回答by Vasil Remeniuk

You can easily implement a richer formatting yourself (with pimp-my-library approach):

您可以自己轻松实现更丰富的格式(使用 pimp-my-library 方法):

scala> implicit def RichFormatter(string: String) = new {
     |   def richFormat(replacement: Map[String, Any]) =
     |     (string /: replacement) {(res, entry) => res.replaceAll("#\{%s\}".format(entry._1), entry._2.toString)}
     | }
RichFormatter: (string: String)java.lang.Object{def richFormat(replacement: Map[String,Any]): String}

scala> "This is #{number} string" richFormat Map("number" -> 1)
res43: String = This is 1 string

回答by Priyank Desai

This the answer I came here looking for:

这是我来这里寻找的答案:

"This is %s string".format(1)

回答by Aldo Bucchi

If you're using 2.10 then go with built-in interpolation. Otherwise, if you don't care about extreme performance and are not afraid of functional one-liners, you can use a fold + several regexp scans:

如果您使用的是 2.10,则使用内置插值。否则,如果您不关心极端性能并且不害怕功能性单行代码,则可以使用折叠 + 几次正则表达式扫描:

val template = "Hello #{name}!"
val replacements = Map( "name" -> "Aldo" )
replacements.foldLeft(template)((s:String, x:(String,String)) => ( "#\{" + x._1 + "\}" ).r.replaceAllIn( s, x._2 ))

回答by Dominik Bucher

You might also consider the use of a template engine for really complex and long strings. On top of my head I have Scalatewhich implements amongst others the Mustachetemplate engine.

您还可以考虑将模板引擎用于非常复杂和长的字符串。在我的头顶上,我有Scalate,它实现了Mustache模板引擎。

Might be overkill and performance loss for simple strings, but you seem to be in that area where they start becoming real templates.

对于简单的字符串来说,这可能是矫枉过正和性能损失,但您似乎正处于它们开始成为真正模板的领域。