| 1 |
let replace ?(pos = 0) ?len ?(all = true) re ~f s = |
| 2 |
if pos < 0 then invalid_arg "Re.replace"; |
| 3 |
let limit = |
| 4 |
match len with |
| 5 |
| None -> String.length s |
| 6 |
| Some l -> |
| 7 |
if l < 0 || pos + l > String.length s then invalid_arg "Re.replace"; |
| 8 |
pos + l |
| 9 |
in |
| 10 |
(* buffer into which we write the result *) |
| 11 |
let buf = Buffer.create (String.length s) in |
| 12 |
(* iterate on matched substrings. *) |
| 13 |
let rec iter pos on_match = |
| 14 |
if pos <= limit |
| 15 |
then ( |
| 16 |
match |
| 17 |
Compile.match_str ~groups:true ~partial:false re s ~pos ~len:(limit - pos) |
| 18 |
with |
| 19 |
| Match substr -> |
| 20 |
let p1, p2 = Group.offset substr 0 in |
| 21 |
if pos = p1 && p1 = p2 && on_match |
| 22 |
then ( |
| 23 |
(* if we matched an empty string right after a match, |
| 24 |
we must manually advance by 1 *) |
| 25 |
if p2 < limit then Buffer.add_char buf s.[p2]; |
| 26 |
iter (p2 + 1) false) |
| 27 |
else ( |
| 28 |
(* add string between previous match and current match *) |
| 29 |
Buffer.add_substring buf s pos (p1 - pos); |
| 30 |
(* what should we replace the matched group with? *) |
| 31 |
let replacing = f substr in |
| 32 |
Buffer.add_string buf replacing; |
| 33 |
if all |
| 34 |
then |
| 35 |
(* if we matched an empty string, we must manually advance by 1 *) |
| 36 |
iter |
| 37 |
(if p1 = p2 |
| 38 |
then ( |
| 39 |
(* a non char could be past the end of string. e.g. $ *) |
| 40 |
if p2 < limit then Buffer.add_char buf s.[p2]; |
| 41 |
p2 + 1) |
| 42 |
else p2) |
| 43 |
(p1 <> p2) |
| 44 |
else Buffer.add_substring buf s p2 (limit - p2)) |
| 45 |
| Running _ -> () |
| 46 |
| Failed -> Buffer.add_substring buf s pos (limit - pos)) |
| 47 |
in |
| 48 |
iter pos false; |
| 49 |
Buffer.contents buf |
| 50 |
;; |
| 51 |
|
| 52 |
let replace_string ?pos ?len ?all re ~by s = replace ?pos ?len ?all re s ~f:(fun _ -> by) |