Skip to content

Commit fb0e357

Browse files
authored
Add some string matching utils (#263)
Splitting this out from #262 for ease of review; please suggest more maintainable / idomatic ways of implementing these functions if there are such
2 parents 795be0b + 8d81a74 commit fb0e357

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/helpers.ml

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,24 @@ open Base
22

33
let f = Printf.sprintf
44

5-
let string_match ~regexp string =
5+
let string_match ~regexp ?(pos = 0) string =
66
try
7-
let _ = Str.search_forward (Str.regexp regexp) string 0 in
7+
let (_ : int) = Str.search_forward (Str.regexp regexp) string pos in
88
true
99
with Stdlib.Not_found -> false
1010

11+
let rec fold_string_matches ~regexp ~f ~init ?(pos = 0) string =
12+
if string_match ~regexp ~pos string then
13+
let pos = Str.match_end () in
14+
f (fun () -> fold_string_matches ~regexp ~f ~init ~pos string)
15+
else init
16+
17+
let map_string_matches ~regexp ~f string =
18+
fold_string_matches ~regexp ~f:(fun rest -> let v = f () in v :: rest ()) ~init:[] string
19+
20+
let iter_string_matches ~regexp ~f string =
21+
fold_string_matches ~regexp ~f:(fun rest -> f () ; rest ()) ~init:() string
22+
1123
let pr_from_branch branch =
1224
if string_match ~regexp:"^pr-\\([0-9]*\\)$" branch then
1325
(Some (Str.matched_group 1 branch |> Int.of_string), "pull request")

src/helpers.mli

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
val f : ('a, unit, string) format -> 'a
22

3-
val string_match : regexp:string -> string -> bool
3+
val string_match : regexp:string -> ?pos:int -> string -> bool
4+
5+
val fold_string_matches :
6+
regexp:string -> f:((unit -> 'a) -> 'a) -> init:'a -> ?pos:int -> string -> 'a
7+
8+
val map_string_matches : regexp:string -> f:(unit -> 'a) -> string -> 'a list
9+
10+
val iter_string_matches : regexp:string -> f:(unit -> unit) -> string -> unit
411

512
val pr_from_branch : string -> int option * string
613

0 commit comments

Comments
 (0)