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#inspect
or haskell's show :: String -> String
.
The simple lambda function "\"" + _ + "\"" only works for strings without any special characters. For example, the string \" (length 2) should be converted to the string "\\\"" (length 6).
Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello World."
To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.
Bookmark this question. Show activity on this post. Scala has triple quoted strings """String\nString""" to use special characters in the string without escaping.
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:
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 }
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"
This solution is admittedly abusing the reflection api but IMHO still safer and more maintainable than the other proposed solutions.
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> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With