I have a String "b\u00f4lovar" and i was wondering if it's possible to unescape without use Commons-lang. It works but i'm facing a problem on some enviroments and i would like to minimize it (i.e.: it works on my machine but not works on production).
StringEscapeUtils.unescapeJava(variables.getOrElse("name", ""))
How can i unescape it without apache lib?
Thank in advance.
Only Unicode escapes
If you want to unescape only sequences in the format
\u0000
than it is simple to do it with a single regex replace:And the result is
We have to process characters
$
and\
separately, because they are treated as special by thejava.util.regex.Matcher.appendReplacement
method:All escape characters
Unicode character escapes are a bit special: they are not a part of string literals, but a part of the program code. There is a separate phase to replace unicode escapes with characters:
There is a function
StringContext.treatEscapes
in Scala library, that supports all normal escapes from the language specification.So if you want to support unicode escapes and all normal Scala escapes, you can unescape both sequentially: