Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape sequences in Ocaml

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?

like image 318
pbp Avatar asked Apr 17 '12 12:04

pbp


2 Answers

Nice solution from http://caml.inria.fr/mantis/view.php?id=3888:

let unescape s = Scanf.sscanf ("\"" ^ s ^ "\"") "%S%!" (fun u -> u)

like image 104
pbp Avatar answered Oct 09 '22 15:10

pbp


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

like image 25
Kevin Chen Avatar answered Oct 09 '22 15:10

Kevin Chen