Last active
February 3, 2026 08:40
-
-
Save dipamsen/3ce62a6850ab3030cf11f321d8180a16 to your computer and use it in GitHub Desktop.
A tiny regex engine in OCaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type regex = | |
| | Phi | |
| | Eps | |
| | Char of char | |
| | Union of regex * regex | |
| | Concat of regex * regex | |
| | Star of regex;; | |
| let star x = Star x;; | |
| let ( !* ) = star;; | |
| let union x y = Union (x, y);; | |
| let (++) = union;; | |
| let concat x y = Concat (x, y);; | |
| let (^.) = concat;; | |
| let partitions s = let n = String.length s in | |
| List.init (n + 1) (fun i -> String.sub s 0 i, String.sub s i (n - i));; | |
| let rec matches regex str = match regex with | |
| | Eps -> str = "" | |
| | Phi -> false | |
| | Char c -> String.length str = 1 && str.[0] = c | |
| | Union (x, y) -> matches x str || matches y str | |
| | Concat (x, y) -> List.exists (fun (a, b) -> matches x a && matches y b) (partitions str) | |
| | Star x -> str = "" || List.exists (fun (a, b) -> a <> "" && matches x a && matches (Star x) b) (partitions str);; | |
| let a = Char 'a';; | |
| let b = Char 'b';; | |
| let re = ((!* a) ^. (!* b)) ++ ((!* b) ^. (!* a));; | |
| let v1 = matches re "aaabbb";; | |
| let v2 = matches re "bbbaaa";; | |
| let v3 = matches re "ababab";; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment