fredoverflow
fredoverflow

Reputation: 263350

How can I escape special symbols in scala string at runtime?

Is there a general Scala utility method that converts a string to a string literal? 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).

Upvotes: 7

Views: 42531

Answers (2)

Shrey
Shrey

Reputation: 2414

Wrap the String with 3 quotes to represent it as is..

e.g. val str = """ \" """ // str : java.lang.String = \"

Upvotes: 12

Malte Schwerhoff
Malte Schwerhoff

Reputation: 12852

Have a look at Apache Common's StringEscapeUtils class (docs here). escapeJava should get the job done.

Have a look at this example to see it in action (in Java).

Upvotes: 7

Related Questions