Scala:如何获得字符串的转义表示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9913971/
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
Scala: How can I get an escaped representation of a string?
提问by rampion
Basically, what I'd like to do is have:
基本上,我想做的是:
// in foo.scala
val string = "this is a string\nover two lines"
println(string)
println(foo(string))
Do this:
做这个:
% scala foo.scala
this is a string
over two lines
"this is a string\nover two lines"
Basically looking for an analog of ruby's String#inspector haskell's show :: String -> String.
基本上是在寻找 rubyString#inspect或 haskell 的类似物show :: String -> String。
采纳答案by Martin Ring
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.
这个问题有点老了,但我在自己寻找解决方案时偶然发现了它,并且对其他答案不满意,因为它们要么不安全(自己更换东西),要么需要外部库。
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:
我找到了一种使用 scala 标准库(> 2.10.0)获取字符串转义表示的方法,这是安全的。它使用了一个小技巧:
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 toStringmethod. This especially means that the literal is represented the way it would be in code, i.e. escaped and double quoted.
通过运行时反射,您可以轻松获得文字字符串表达式的表示。这种表达式的树在调用它的toString方法时作为(几乎)scala 代码返回。这尤其意味着文字以它在代码中的方式表示,即转义和双引号。
def escape(raw: String): String = {
import scala.reflect.runtime.universe._
Literal(Constant(raw)).toString
}
The escapefunction therefore results in the desired code-representation of the provided raw string (including the surrounding double quotes):
escape因此,该函数会产生所提供原始字符串(包括周围的双引号)的所需代码表示:
scala> "\bHallo" + '\n' + "\tWelt"
res1: String =
?Hallo
Welt
scala> escape("\bHallo" + '\n' + "\tWelt")
res2: String = "\bHallo\n\tWelt"
This solution is admittedly abusing the reflection api but IMHO still safer and more maintainable than the other proposed solutions.
诚然,该解决方案滥用了反射 api,但恕我直言,它仍然比其他提议的解决方案更安全、更易于维护。
回答by Travis Brown
I'm pretty sure this isn't available in the standard libraries for either Scala or Java, but it is in Apache Commons Lang:
我很确定这在 Scala 或 Java 的标准库中不可用,但它在Apache Commons Lang 中:
scala> import org.apache.commons.lang.StringEscapeUtils.escapeJava
import org.apache.commons.lang.StringEscapeUtils.escapeJava
scala> escapeJava("this is a string\nover two lines")
res1: java.lang.String = this is a string\nover two lines
You could easily add the quotation marks to the escaped string if you wanted, of course.
当然,如果您愿意,您可以轻松地将引号添加到转义字符串中。
回答by 0__
The scala.reflect solution actually works fine. When you do not want to pull in that whole library, this is what it seems to do under the hood (Scala 2.11):
scala.reflect 解决方案实际上工作正常。当你不想拉入整个库时,这就是它在幕后所做的事情(Scala 2.11):
def quote (s: String): String = "\"" + escape(s) + "\""
def escape(s: String): String = s.flatMap(escapedChar)
def escapedChar(ch: Char): String = ch match {
case '\b' => "\b"
case '\t' => "\t"
case '\n' => "\n"
case '\f' => "\f"
case '\r' => "\r"
case '"' => "\\""
case '\'' => "\\'"
case '\' => "\\"
case _ => if (ch.isControl) "\0" + Integer.toOctalString(ch.toInt)
else String.valueOf(ch)
}
val string = "\"this\" is a string\nover two lines"
println(quote(string)) // ok
回答by Eve Freeman
You could build your own function pretty easily, if you don't want to use the apache library:
如果您不想使用 apache 库,您可以很容易地构建自己的函数:
scala> var str = "this is a string\b with some \n escapes \t so we can \r \f \' \" see how they work \";
str: java.lang.String =
this is a string? with some
escapes so we can
' " see how they work \
scala> print(str.replace("\","\\").replace("\n","\n").replace("\b","\b").replace("\r","\r").replace("\t","\t").replace("\'","\'").replace("\f","\f").replace("\"","\\""));
this is a string\b with some \n escapes \t so we can \r \f \' \" see how they work \
回答by user unknown
If I compile these:
如果我编译这些:
object s1 {
val s1 = "this is a string\nover two lines"
}
object s2 {
val s2 = """this is a string
over two lines"""
}
I don't find a difference in the String, so I guess: There is no possibility, to find out, whether there was was a "\n" in the source.
我没有发现 String 有什么不同,所以我猜:没有可能找出源中是否有“\n”。
But maybe I got you wrong, and you would like to get the same result for both?
但也许我误会了你,你想得到相同的结果吗?
"\"" + s.replaceAll ("\n", "\\n").replaceAll ("\t", "\\t") + "\""
The second possibility is:
第二种可能是:
val mask = Array.fill (3)('"').mkString
mask + s + mask
res5: java.lang.String =
"""a
b"""
Test:
测试:
scala> val s = "a\n\tb"
s: java.lang.String =
a
b
scala> "\"" + s.replaceAll ("\n", "\\n").replaceAll ("\t", "\\t") + "\""
res7: java.lang.String = "a\n\tb"
scala> mask + s + mask
res8: java.lang.String =
"""a
b"""

