View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ocaml
#load "str.cma" ;;

let s = "one two three" in
if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then
print_string (Str.matched_group 1 s)

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
ocaml
#load "str.cma" ;;

let re = Str.regexp "[0-9]+" in
try let _ = Str.search_forward re "abc 123 @#$" 0 in
print_string "ok"
with _ -> ()

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
ocaml
let result =
let str = "(fish):1 sausage (cow):3 tree (boat):4" in
let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in
Array.to_list (
Array.map (fun m ->
let s = Pcre.get_substrings m in
Printf.sprintf "%s%s" s.(1) s.(2);
) ms
)

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
ocaml
let replaced = Str.replace_first (Str.regexp "e") "*" "Red Green Blue" in
print_endline replaced ;;

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
ocaml
let s = "She sells sea shells" in
Str.global_replace (Str.regexp "se[^ \\t\\n]*") "X" s

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
ocaml
let s = "The {Quick} Brown {Fox}" in
let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in
Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s