I just try to use re2 to replace a regex in a file, the test was passed for a simple string.
# module Re2 = Re2.Std.Re2;;
# let re = Re2.create_exn "<key>Tags.*<\\/array>" ;;
# let orig = "abc <key>Tags</key><array><string>OCaml</string></array> end";;
# Re2.replace_exn ~f:(fun _ -> "<key>Tags</key><array/>") re orig;;
- : string = "abc <key>Tags</key><array/> end"
However, when I put the contents into file as ss.xml
:
<key>Starred</key>
<false/>
<key>Tags</key>
<array>
<string>Think</string>
<string>Performance Test</string>
<string>Racket</string>
<string>OCaml</string>
</array>
<key>Time Zone</key>
<string>Asia/Shanghai</string>
The OCaml source code:
open Core.Std
open Async.Std
module Re2 = Re2.Std.Re2
let trans_reg (input: string) : string =
let re = Re2.create_exn "<key>Tags.*<\\/array>" in
let target = "<key>Tags</key><array/>" in
Re2.replace_exn ~f:(fun _ -> target) re input
let handle_file (filename: string) =
let%bind text = Reader.file_contents filename in
Writer.save (filename ^ ".xml") ~contents:(trans_reg text)
let () =
Command.(run (async ~summary:"" Spec.empty (fun _ -> handle_file "ss.xml")))
Nothing's gonna change in my new file ss.xml.xml
.
I was wondering:
- How to regex match in this case.
- When shall we use the parameter of replace
Match.t
in~f:(Match.t -> string)
? ()