diff --git a/src/tyre.ml b/src/tyre.ml index 64f9447..d784d04 100644 --- a/src/tyre.ml +++ b/src/tyre.ml @@ -403,6 +403,14 @@ let[@inline] exec ?pos ?len ({ info ; cre } as tcre) original = with exn -> Result.Error (`ConverterFailure exn) +let replace ?pos ?len ?all ({ info ; cre }) f original = + try + Ok ( + Re.replace ?pos ?len ?all cre original + ~f:(fun subs -> f (extract_with_info ~info ~original subs)) + ) + with exn -> Result.Error (`ConverterFailure exn) + let execp ?pos ?len {cre ; _ } original = Re.execp ?pos ?len cre original diff --git a/src/tyre.mli b/src/tyre.mli index 8849793..b87268d 100644 --- a/src/tyre.mli +++ b/src/tyre.mli @@ -1,6 +1,6 @@ (** {1 Typed regular expressions} *) -(** +(** Tyre is a set of combinators to build type-safe regular expressions, allowing automatic extraction and modification of matched groups. Tyre is bi-directional: a typed regular expressions can be used both for {{!matching}matching} and {{!eval}evaluation}. Multiple tyregexs can be combined in order to do {{!routing}routing} in similar manner as switches/pattern matching. @@ -40,7 +40,7 @@ type 'a t (** {1 Combinators} *) val pcre : string -> string t -(** [pcre s] is a tyregex that matches the PCRE [s] and return the +(** [pcre s] is a tyregex that matches the PCRE [s] and return the corresponding string. Groups in [s] are ignored. *) @@ -222,6 +222,11 @@ val execp : ?pos:int -> ?len:int -> 'a re -> string -> bool @since 0.1.1 *) +val replace : ?pos:int -> ?len:int -> ?all:bool -> 'a re -> ('a -> string) -> string -> (string, [> `ConverterFailure of exn ]) result +(** [replace r f s] returns [s] where every match of [r] has been + replaced by [f v] where [v] is the value associated with [r]. + If [all] is set to [false], it only replaces the first match. *) + (** {2:repeat Repeated Matching} *) diff --git a/test/test.ml b/test/test.ml index 378883e..1d772e3 100644 --- a/test/test.ml +++ b/test/test.ml @@ -181,6 +181,22 @@ let route_test = [ troute "route 4" "xxblob" 4 "xx" ; ] +let treplace title s tyre f result = + let tyre = compile tyre in + title, `Quick, + fun () -> + A.(check @@ result (string) reject) + title (replace tyre f s) (Ok result) + +let replace_test = [ + treplace + "mult2" + "foo123 134 45678" + int + (fun i -> string_of_int (i * 2)) + "foo246 268 91356" +] + let () = Alcotest.run "tyre" [ "basics", basics ; @@ -191,4 +207,5 @@ let () = Alcotest.run "tyre" [ "routes", route_test ; "nomatch", nomatch ; "convfail", conv_failure ; + "replace", replace_test ]