module Js_re:sig
..end
[%re "/foo/g"]
will evaluate to a Js_re.t
that can be passed around and used like usual.
Note: This is not an immutable API. A RegExp object with the global
("g")
flag set will modify the Js_re.lastIndex
property when the RegExp object is used,
and subsequent uses will ocntinue the search from the previous Js_re.lastIndex
.
let maybeMatches = "banana" |> Js.String.match_ [[%re "/na+/g"]]
type
t
type
result
val matches : result -> string array
val index : result -> int
val input : result -> string
val fromString : string -> t
Js_re.t
) from a string
Regex literals ([%re "/.../"]
) should generally be preferred, but
fromString
is very useful when you need to insert a string into a regex.
(* A function that extracts the content of the first element with the given tag *) let contentOf tag xmlString = Js.Re.fromString ("<" ^ tag ^ ">(.|\n)*?<\/" ^ tag ^">") |> Js.Re.exec xmlString |> function | Some result -> Some (Js.Re.matches result).(1) | None -> None
val fromStringWithFlags : string -> flags:string -> t
Js_re.t
) from a string with the given flags
See Js_re.fromString
Valid flags:
g | global | |
i | ignore case | |
m | multiline | |
u | unicode | (es2015) |
y | sticky | (es2015) |
val flags : t -> string
val global : t -> bool
global
flag is setval ignoreCase : t -> bool
ignoreCase
flag is setval lastIndex : t -> int
This property will be modified when the RegExp object is used, if the global
("g")
flag is set.
(* Finds and prints successive matches *) let re = [%re "/ab*/g"] in let str = "abbcdefabh" in let break = ref false in while not !break do match re |> Js.Re.exec str with | None -> break := true | Some result -> let match_ = (Js.Re.matches result).(0) in let next = string_of_int (Js.Re.lastIndex re) in Js.log ("Found " ^ match_ ^ ". Next match starts at " ^ next) done
val setLastIndex : t -> int -> unit
val multiline : t -> bool
multiline
flag is setval source : t -> string
val sticky : t -> bool
sticky
flag is setval unicode : t -> bool
unicode
flag is setval exec : string -> t -> result option
returns Some
Js_re.result
if a match is found, None
otherwise
(* Match "quick brown" followed by "jumps", ignoring characters in between * Remember "brown" and "jumps" * Ignore case *) let re = [%re "/quick\s(brown).+?(jumps)/ig" in let result = re |> Js.Re.exec "The Quick Brown Fox Jumps Over The Lazy Dog"
val test : string -> t -> bool
returns true
if a match is found, false
otherwise
(* A simple implementation of Js.String.startsWith *) let str = "hello world!" let startsWith substring target = Js.Re.fromString ("^" ^ substring) |> Js.Re.test target let () = Js.log (str |> startsWith "hello") (* prints "true" *)