Scala:如何获得字符串的转义表示? [英] Scala: How can I get an escaped representation of a string?

查看:192
本文介绍了Scala:如何获得字符串的转义表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想做的是:

 // in foo.scala
 val string = "this is a string\nover two lines"
 println(string)
 println(foo(string))

执行此操作:

% scala foo.scala
this is a string
over two lines
"this is a string\nover two lines"

基本上寻找一个模仿ruby的 String#inspect 或haskell的 show :: String - >字符串

Basically looking for an analog of ruby's String#inspect or haskell's show :: String -> String.

推荐答案

这个问题有点旧,但我在搜索解决方案时偶然发现我自己也不满意其他的答案,因为他们不安全(替换自己的东西)或需要一个外部图书馆。

This question is a bit old but I stumbled over it while searching for a solution myself and was dissatisfied with the other answers because they either are not safe (replacing stuff yourself) or require an external library.

我找到了一种方式来获得转义的代表一个字符串与Scala标准库(> 2.10.0)是安全的。它使用一个小技巧:

I found a way to get the escaped representation of a string with the scala standard library (>2.10.0) which is safe. It uses a little trick:

通过运行时反射,您可以轻松获取文字字符串表达式的表示。当调用它的 toString 方法时,这样一个表达式的树被返回为(几乎)scala代码。这意味着字面值代表了代码的方式,即转义和双引号。

Through runtime reflection you can can easily obtain a representation of a literal string expression. The tree of such an expression is returned as (almost) scala code when calling it's toString method. This especially means that the literal is represented the way it would be in code, i.e. escaped and double quoted.

def escape(raw: String): String = {
  import scala.reflect.runtime.universe._
  Literal(Constant(raw)).toString
}

因此, escape 函数会导致所提供的原始字符串所需的代码表示(包括周围的双引号):

The escape function therefore results in the desired code-representation of the provided raw string (including the surrounding double quotes):

scala> "\bHallo" + '\n' + "\tWelt"
res1: String =
?Hallo
        Welt

scala> escape("\bHallo" + '\n' + "\tWelt")
res2: String = "\bHallo\n\tWelt"

这个解决方案肯定是滥用反射api,但是IMHO比其他提出的解决方案更安全和更易于维护。

This solution is admittedly abusing the reflection api but IMHO still safer and more maintainable than the other proposed solutions.

这篇关于Scala:如何获得字符串的转义表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆