Is there a standard way in Ocaml, to convert from (for example) a\n
(a three byte string: 0x61,0x5c,0x6e
) to a two byte string: 0x61,0x0a
?
My Ocaml program can receive strings with escaped characters, how to "unescape" them?
Nice solution from http://caml.inria.fr/mantis/view.php?id=3888:
let unescape s =
Scanf.sscanf ("\"" ^ s ^ "\"") "%S%!" (fun u -> u)
If you are using OCaml 4.0.0 or later, you can use Scanf.unescaped
.
Example:
# open Scanf
# Scanf.unescaped "a\\n";;
- : bytes = "a\n"
# Scanf.unescaped "\\n\\t\\\\";;
- : bytes = "\n\t\\"
Interface: (via OCaml docs)
val unescaped : string -> string
Return a copy of the argument with escape sequences, following the lexical conventions of OCaml, replaced by their corresponding special characters. If there is no escape sequence in the argument, still return a copy, contrary to String.escaped.
Since 4.00.0
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