How can I delete a line in scala?

I've found a lot of posts about string escaping, but not about canceling escaping.

Using Scala Play, my controller accepts JSON as a request. I extract the string from it via:

val text: play.api.libs.json.JsValue = request.body.\("source")

      

If I type text.toString

I get for example

"Hello\tworld\nmy name is \"ABC\""

      

How can I convert this escaped text to normal? The result should look like

Hello    world
my name is "ABC"

      

Up to this point, I have tried this approach:

replaceAll("""\\t""", "\t")

      

However, creating all the possible escaping rules can be overwhelming. So my question is how to do this? It is possible to use the standard library. Java solutions are also possible.

+3


source to share


3 answers


There are interpolations that allow you to convert strings to formatted and / or escaped sequences. These interpolations such as s"..."

or f"..."

are handled in StringContext .

It also offers the opposite function:



val es = """Hello\tworld\nmy name is \"ABC\""""
val un = StringContext treatEscapes es

      

+10


source


You have to use the unescape method from the scala standard library. Below is a link to the documentation that you will find at the right end of the Value section.



+2


source


This is not an answer to canceling lines in general, but specifically for handling JsValue

:

text match { 
  case JsString(value) => value
  case _ => // what do you want to do for other cases?
}

      

You can implement unescape this way:

def unescapeJson(s: String) = JSON.parse('"' + s + '"') match {
  case JsString(value) => value
  case _ => ??? // can't happen
}

      

or use StringEscapeUtils

from Apache Commons Lang (it's a pretty big dependency though).

0


source







All Articles