From 447d4d3f1f5e1158f818cad1733594a750e35548 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Sat, 12 Oct 2024 10:41:50 +0100 Subject: [PATCH] feature(pcre): get_named_substring_opt --- CHANGES.md | 6 ++++++ lib/pcre.ml | 18 +++++++++++++----- lib/pcre.mli | 6 +++++- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 08c921ca..758bba08 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,9 @@ +Unreleased +---------- + +* Introduce [Re.Pcre.get_named_substring_opt]. A non raising version of + [Re.Pcre.get_named_substring] (#525) + 1.13.1 (30-Sep-2024) -------------------- diff --git a/lib/pcre.ml b/lib/pcre.ml index 62875949..bfcde7b9 100644 --- a/lib/pcre.ml +++ b/lib/pcre.ml @@ -36,15 +36,15 @@ let re ?(flags = []) pat = let regexp ?flags pat = Re.compile (re ?flags pat) let extract ~rex s = Re.Group.all (Re.exec rex s) let exec ~rex ?pos s = Re.exec rex ?pos s -let get_substring s i = Re.Group.get s i let names rex = Re.group_names rex |> List.map fst |> Array.of_list -let get_named_substring rex name s = +let get_named_substring_opt rex name s = let rec loop = function - | [] -> raise Not_found + | [] -> None | (n, i) :: rem when n = name -> - (try get_substring s i with - | Not_found -> loop rem) + (match Re.Group.get_opt s i with + | None -> loop rem + | Some _ as s -> s) | _ :: rem -> loop rem in loop (Re.group_names rex) @@ -169,3 +169,11 @@ let full_split ?(max = 0) ~rex s = ;; type substrings = Group.t + +let get_substring s i = Re.Group.get s i + +let get_named_substring rex name s = + match get_named_substring_opt rex name s with + | None -> raise Not_found + | Some s -> s +;; diff --git a/lib/pcre.mli b/lib/pcre.mli index 56424a9d..76f3b543 100644 --- a/lib/pcre.mli +++ b/lib/pcre.mli @@ -39,9 +39,13 @@ val get_substring : groups -> int -> string (** Return the names of named groups. *) val names : regexp -> string array -(** Return the first matched named group, or raise [Not_found]. *) +(** Return the first matched named group, or raise [Not_found]. Prefer to use + the non-raising version [get_named_substring_opt] *) val get_named_substring : regexp -> string -> groups -> string +(** Return the first matched named group, or raise [Not_found]. *) +val get_named_substring_opt : regexp -> string -> groups -> string option + (** Equivalent to {!Core.Group.offset}. *) val get_substring_ofs : groups -> int -> int * int