Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to de-escape string in scala?

I found many posts about escaping string but no about de-escaping one.

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

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

If I print text.toString I get e.g.

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

How can I transform this escaped text into normal one? The result should look like

Hello    world
my name is "ABC"

Up to this point, I've tried an approach like it follows:

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

However, creating all possible escaping rules may be too complicated. So my question is: How to do that easily? Possibly using standard library. Java solutions are also possible.

like image 315
petrbel Avatar asked Apr 29 '15 06:04

petrbel


People also ask

How do you escape a string from a string?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.

What is the use of escape string?

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").

How do I escape a string in JSON?

JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020). This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character.


2 Answers

There are interpolations which allow you to transform Strings into formatted and/or escaped sequences. These interpolations like s"..." or f"..." are handled in StringContext.

It also offers a reverse function:

val es = """Hello\tworld\nmy name is \"ABC\""""
val un = StringContext treatEscapes es
like image 170
Flown Avatar answered Oct 11 '22 14:10

Flown


This isn't an answer for unescaping strings 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 in 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 (though this is a rather large dependency).

like image 27
Alexey Romanov Avatar answered Oct 11 '22 14:10

Alexey Romanov