### Test Regex Match at Start of String Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Tests if a compiled regular expression matches at the beginning of a given string. The `start` parameter specifies the position to begin the match. ```ocaml let regex = Re.Str.regexp "^[a-z]+" Re.Str.string_match regex "hello 123" 0 (* true *) Re.Str.string_match regex "123 hello" 0 (* false *) ``` -------------------------------- ### Lazy Sequence of All Matches Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Seq.all` to get matches as a lazy sequence, which is memory-efficient for large inputs. This example iterates and prints each full match. ```ocaml let regex = Re.compile Re.(seq [str "my"; blank; word (rep alpha)]) let seq = Re.Seq.all regex "my head, my shoulders, my knees" Seq.iter (fun group -> printf "%s\n" (Re.Group.get group 0)) seq ``` -------------------------------- ### String Regular Expression Matching Examples Source: https://github.com/ocaml/ocaml-re/blob/master/TODO.txt Demonstrates matching behavior for String regular expressions with different inputs and expected outputs. ```regex " (a?)*" "b" no submatch " (a?)*" "ab" "a" ``` ```regex " ((a)|(b))*" "ab" -> "b" "a" "b" ``` -------------------------------- ### Re.Str.match_beginning Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Returns the starting position of the last successful regular expression match. ```APIDOC ## Re.Str.match_beginning : unit -> int ### Description Returns the starting position of the last match. ### Method `match_beginning` ### Response #### Success Response - **int** (int) - The starting position of the last match. ``` -------------------------------- ### Emacs Regular Expression Matching Examples Source: https://github.com/ocaml/ocaml-re/blob/master/TODO.txt Demonstrates matching behavior for Emacs regular expressions with different inputs and expected outputs. ```regex " (a?)*" "b" "" " (a?)*" "ab" "" ``` ```regex " (a?)*?" "b" "" " (a?)*?" "ab" "a" ``` ```regex " ((a)|(b))*" "ab" -> "b" "a" "b" ``` -------------------------------- ### POSIX Regular Expression Matching Examples Source: https://github.com/ocaml/ocaml-re/blob/master/TODO.txt Demonstrates matching behavior for POSIX regular expressions with different inputs and expected outputs. ```regex " (a?)*" "b" "" " (a?)*" "ab" "a" ``` ```regex " ((a)|(b))*" "ab" -> "b" none "b" ``` -------------------------------- ### Javascript Regular Expression Matching Examples Source: https://github.com/ocaml/ocaml-re/blob/master/TODO.txt Demonstrates matching behavior for Javascript regular expressions with different inputs and expected outputs. ```regex " (a?)*" "b" no submatch " (a?)*" "ab" "a" ``` ```regex " ((a)|(b))*" "ab" -> "b" none "b" ``` -------------------------------- ### PCRE Regular Expression Matching Examples Source: https://github.com/ocaml/ocaml-re/blob/master/TODO.txt Demonstrates matching behavior for PCRE regular expressions with different inputs and expected outputs. ```regex " (a?)*" "b" "" " (a?)*" "ab" "" ``` ```regex " (a?)*?" "b" "" " (a?)*?" "ab" "a" ``` ```regex " ((a)|(b))*" "ab" -> "b" "a" "b" ``` -------------------------------- ### Example Usage of Split Token Type Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Demonstrates the usage of the split_token type with the split_full function to parse a delimited string. ```ocaml type split_token = [ `Text of string | `Delim of Group.t ] let tokens = Re.split_full (Re.compile (Re.char ',')) "a,b,c" (* [`Text "a"; `Delim ; `Text "b"; `Delim ; `Text "c"] *) ``` -------------------------------- ### OCaml Str Full Split Example Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Demonstrates the usage of `Re.Str.full_split` with a regular expression to split a string and return a list of `split_result` tokens. ```ocaml let regex = Re.Str.regexp "[,:]" let tokens = Re.Str.full_split regex "a,b:c,d" (* [Text "a"; Delim ","; Text "b"; Delim ":"; Text "c"; Delim ","; Text "d"] *) ``` -------------------------------- ### PCRE Full Split Example Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Demonstrates how to use Pcre.full_split with a regex that captures numeric groups to split a string. Shows the resulting list of Text and Group tokens. ```ocaml let regex = Re.Pcre.regexp "([0-9]+)" let tokens = Re.Pcre.full_split ~rex:regex "a 1 b 2 c" (* [Text "a "; Group (1, "1"); Text " b "; Group (1, "2"); Text " c"] *) ``` -------------------------------- ### all Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Returns all matches in the string as a list of group objects. Allows specifying start position and length for the search. ```APIDOC ## all ### Description Returns all matches in the string as a list of group objects. Allows specifying start position and length for the search. ### Method `all : ?pos:int -> ?len:int -> re -> string -> Group.t list` ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position (default: 0) - **len** (int) - Optional - Length of substring to search (default: -1) - **re** (re) - Required - Compiled regular expression - **string** (string) - Required - String to search ### Response #### Success Response - **Group.t list** - List of all matches found. ### Request Example ```ocaml let regex = Re.compile Re.(seq [str "my"; blank; word (rep alpha)]) let matches = Re.all regex "my head, my shoulders, my knees" (* Returns 3 Group.t objects for "my head", "my shoulders", "my knees" *) ``` ``` -------------------------------- ### Compile POSIX ERE with Options Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/02-perl-posix-emacs.md Compiles a POSIX ERE pattern using specified parsing options. This example demonstrates case-insensitive matching. ```ocaml Re.Posix.compile_pat ~opts:[`ICase] "[A-Z]" ``` -------------------------------- ### Perl Regex Parsing Options Example Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/02-perl-posix-emacs.md Demonstrates the use of parsing options with Perl-style regex compilation. Options like `Caseless` and `Multiline` can be passed to `compile_pat` to modify matching behavior. ```ocaml Re.Perl.compile_pat ~opts:[`Caseless; `Multiline] "[a-z]+" ``` -------------------------------- ### Regex Matching with Position and Length Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Control the starting position and search length for regex matching operations. ```ocaml Re.exec regex ~pos:5 "hello world" (* Start at position 5 *) Re.exec regex ~len:5 "hello world" (* Search only first 5 chars *) Re.exec regex ~pos:2 ~len:8 string (* From pos 2, length 8 *) ``` -------------------------------- ### OCaml-re Module Functionality Overview Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/INDEX.md This table summarizes the functions, examples, and types documented for each module within the OCaml-re library. It serves as a quick reference for the library's scope and content. ```markdown | Module | Functions | Examples | |--------|-----------|----------| | Re.Core | 76 | 1 per function | | Re.Perl | 4 | 3 | | Re.Posix | 4 | 3 | | Re.Emacs | 3 | 2 | | Re.Glob | 2 | 2 | | Re.Pcre | 15 | 8 | | Re.Str | 31 | 10 | | Re.Replace | 2 | 2 | | Re.Group | 13 | 3 | | Re.Mark | 4 | 2 | | Re.Seq | 5 | 1 | | Re.Stream | 5 | 1 | | Re.View | 1 | — | ``` -------------------------------- ### Detailed Partial Regex Match Analysis Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `exec_partial_detailed` to get group information on a full match or the earliest possible start position on a partial match. Returns `Mismatch` if no match is possible. ```ocaml match Re.exec_partial_detailed regex "// comment" with | `Full groups -> printf "Matched" | `Partial pos -> printf "Could match if extended from position %d" pos | `Mismatch -> printf "No match" ``` -------------------------------- ### Simple String Replacement Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Use `replace_string` for basic string replacements. Specify `all: false` to replace only the first occurrence or `pos` to start from a specific index. ```ocaml Re.replace_string regex ~by:"X" "hello" (* Replace all *) Re.replace_string regex ~all:false ~by:"X" "hello" (* Replace first *) Re.replace_string regex ~pos:2 ~by:"X" "hello" (* Start from pos 2 *) ``` -------------------------------- ### Execute Regex and Get Optional Groups Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `exec_opt` for a non-exception-raising version of `exec`. It returns `Some groups` on a match or `None` if no match is found. ```ocaml let regex = Re.compile Re.(seq [str "//"; rep print]) match Re.exec_opt regex "# a comment" with | Some groups -> printf "Matched" | None -> printf "No match" ``` -------------------------------- ### Extract Named Regex Groups (OCaml) Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Define named groups using `Re.group ~name:"..."` and retrieve their names and indices. This example shows how to compile and get group names. ```ocaml let regex = Re.compile Re.(group ~name:"word" (rep alpha)) let names = Re.group_names regex (* [("word", 1)] *) ``` -------------------------------- ### Search Forward for Regex Match Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Searches forward in a string for the first occurrence of a compiled regular expression, starting from a specified position. Returns the starting index of the match. ```ocaml let regex = Re.Str.regexp "[a-z]+" let pos = Re.Str.search_forward regex "123 hello" 0 (* 4 *) ``` -------------------------------- ### matches Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Returns all matched substrings, providing a simpler interface than `all` when only the matched text is needed. Supports specifying start position and length. ```APIDOC ## matches ### Description Returns all matched substrings, providing a simpler interface than `all` when only the matched text is needed. Supports specifying start position and length. ### Method `matches : ?pos:int -> ?len:int -> re -> string -> string list` ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position (default: 0) - **len** (int) - Optional - Length of substring to search (default: -1) - **re** (re) - Required - Compiled regular expression - **string** (string) - Required - String to search ### Response #### Success Response - **string list** - List of all matched substrings. ### Request Example ```ocaml let regex = Re.compile Re.(seq [str "my"; blank; word (rep alpha)]) let strs = Re.matches regex "my head, my shoulders, my knees" (* ["my head"; "my shoulders"; "my knees"] *) ``` ``` -------------------------------- ### Execute Regex and Get Groups Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `exec` to find the earliest match of a compiled regex in a string and retrieve captured groups. Raises `Not_found` if no match occurs. ```ocaml let regex = Re.compile Re.(seq [str "//"; rep print]) let groups = Re.exec regex "// a C comment" let matched = Re.Group.get groups 0 (* "// a C comment" *) ``` -------------------------------- ### exec_partial_detailed Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Extends `exec_partial` by returning group information on a full match or a position hint on a partial match. It returns `` `Full of Group.t `` for a complete match, `` `Partial of int `` indicating the earliest possible start position for a partial match, or `` `Mismatch `` if no match occurs. Optional `pos` and `len` parameters define the search range. ```APIDOC ## exec_partial_detailed : ?pos:int -> ?len:int -> re -> string -> [ `Full of Group.t | `Partial of int | `Mismatch ] ### Description Like `exec_partial` but returns the group on full match and a position hint on partial match. ### Method OCaml function call ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position in the string - **len** (int) - Optional - Length of substring to search - **re** (re) - Required - Compiled regular expression - **string** (string) - Required - String to search ### Returns - `` `Full of Group.t `` — Complete match with group information - `` `Partial of int `` — Partial match; int indicates earliest position where match could start - `` `Mismatch `` — No match possible ### Example ```ocaml match Re.exec_partial_detailed regex "// comment" with | `Full groups -> printf "Matched" | `Partial pos -> printf "Could match if extended from position %d" pos | `Mismatch -> printf "No match" ``` ``` -------------------------------- ### Re.Str.group_beginning Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Returns the starting position of a specific capturing group (n) in the last regular expression match. ```APIDOC ## Re.Str.group_beginning : int -> int ### Description Returns the starting position of group n. ### Method `group_beginning` ### Parameters #### Path Parameters - **n** (int) - Required - Group number (1-based). ### Response #### Success Response - **int** (int) - The starting position of group n. ``` -------------------------------- ### Extract Regex Groups by Index Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Use `Re.exec` to get the first match and then `Re.Group.get` or `Re.Group.get_opt` to extract specific groups by their index. Offsets and positions can also be retrieved. ```ocaml let groups = Re.exec regex "hello world" Re.Group.get groups 0 (* Whole match *) Re.Group.get groups 1 (* First group *) Re.Group.get_opt groups 2 (* Returns option *) let (start, end_) = Re.Group.offset groups 1 (* Position of group 1 *) let start = Re.Group.start groups 1 (* Start position *) let end_ = Re.Group.stop groups 1 (* End position *) ``` -------------------------------- ### Case-Insensitive Matching Example Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Re.no_case` to perform case-insensitive matching with a regular expression. This is useful when the case of the matched text is not important. ```ocaml Re.no_case (Re.str "Hello") (* Matches "hello", "HELLO", "HeLLo", etc. *) ``` -------------------------------- ### Check Regex Matches at Specific Positions Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Verify if a regex pattern matches a string starting from a specific position (`~pos`) or within a limited length (`~len`). This is useful for partial validation or targeted searching. ```ocaml let regex = Re.compile Re.(seq [str "hello"; space; word (rep alpha)]) (* From position 0 *) Re.execp regex ~pos:0 "hello world" (* true *) (* From position 5 *) Re.execp regex ~pos:5 "xxx hello world" (* true *) (* With limited length *) Re.execp regex ~len:5 "hello xyz" (* false - pattern needs more than 5 chars *) ``` -------------------------------- ### Re.Stream Functions Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/07-module-index.md An experimental API for incremental input processing using a streaming matcher. It allows creating a stream, feeding it with chunks of data, and finalizing the process to get match results. ```APIDOC ## Re.Stream: Streaming Matcher Experimental API for feeding input incrementally. ### Types | Type | |------| | `t` | | `'a feed` | ### Functions | Function | |----------| | `create` | | `feed` | | `finalize` | ### Purpose - `create`: Create stream - `feed`: Feed chunk - `finalize`: Finalize ### Submodules - **Stream.Group**: `create`, `feed`, `finalize` - **Stream.Group.Match**: `get`, `test_mark` ``` -------------------------------- ### split_delim Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Similar to `split`, but preserves empty strings at the start or end if delimiters appear there. Supports specifying start position and length. ```APIDOC ## split_delim ### Description Similar to `split`, but preserves empty strings at the start or end if delimiters appear there. Supports specifying start position and length. ### Method `split_delim : ?pos:int -> ?len:int -> re -> string -> string list` ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position (default: 0) - **len** (int) - Optional - Length of substring to search (default: -1) - **re** (re) - Required - Compiled regular expression (the delimiter) - **string** (string) - Required - String to split ### Response #### Success Response - **string list** - Substrings between delimiters, including empty strings. ### Request Example ```ocaml let regex = Re.compile (Re.char ',') Re.split_delim regex ",1,2," (* [""; "1"; "2"; ""] *) ``` ``` -------------------------------- ### Re.Str.string_partial_match Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Checks if a regular expression matches a prefix of a string starting at a specified position. ```APIDOC ## Re.Str.string_partial_match : regexp -> string -> int -> bool ### Description Like `string_match` but succeeds if the string is a prefix of a matching string. ### Method `string_partial_match` ### Parameters #### Path Parameters - **regexp** (`regexp`) - Required - Compiled regex. - **string** (string) - Required - String to search. - **start** (int) - Required - Starting position. ### Response #### Success Response - **bool** (bool) - True if the string is a prefix of a match. ``` -------------------------------- ### Re.Str.search_backward Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Searches backward in a string for a regular expression match, returning the starting position of the match. ```APIDOC ## Re.Str.search_backward : regexp -> string -> int -> int ### Description Like `search_forward` but searches backward from the given position. ### Method `search_backward` ### Parameters #### Path Parameters - **regexp** (`regexp`) - Required - Compiled regex. - **string** (string) - Required - String to search. - **start** (int) - Required - Starting position. ### Response #### Success Response - **int** (int) - Position of the first character of the match. #### Error Response - **Not_found** - If no match is found. ``` -------------------------------- ### Re.Str.search_forward Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Searches forward in a string for a regular expression match, returning the starting position of the match. ```APIDOC ## Re.Str.search_forward : regexp -> string -> int -> int ### Description Searches forward for a match, returning the position of the first character of the match. ### Method `search_forward` ### Parameters #### Path Parameters - **regexp** (`regexp`) - Required - Compiled regex. - **string** (string) - Required - String to search. - **start** (int) - Required - Starting position. ### Request Example ```ocaml let regex = Re.Str.regexp "[a-z]+" let pos = Re.Str.search_forward regex "123 hello" 0 (* 4 *) ``` ### Response #### Success Response - **int** (int) - Position of the first character of the match. #### Error Response - **Not_found** - If no match is found. ``` -------------------------------- ### Compiling Regex with Options and Handling Errors Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Illustrates how to compile a Perl-style regex with specific options (case-insensitivity, multiline) and handle potential compilation errors. This is useful for creating robust regex patterns. ```ocaml let pattern = Re.Perl.re_result ~opts:[`Caseless; `Multiline] "[a-z]+" match pattern with | Ok p -> let regex = Re.compile p in printf "Match: %b\n" (Re.execp regex "HELLO") | Error `Parse_error -> printf "Syntax error" | Error `Not_supported -> printf "Unsupported" ``` -------------------------------- ### Str Module Compatibility Quick Functions Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Provides `string_match` for boolean checks from a position, `search_forward` to find the next match, and functions to retrieve matched text and groups. ```ocaml let regex = Re.Str.regexp "[a-z]+" Re.Str.string_match regex "hello" 0 (* Boolean from position *) Re.Str.search_forward regex "a hello b" 0 (* Find position *) let text = Re.Str.matched_string "a hello b" (* Last matched text *) let word = Re.Str.matched_group 1 "hello" (* Group text *) Re.Str.global_replace regex "X" "hello" (* Replace all *) Re.Str.global_substitute regex String.uppercase_ascii "hello" ``` -------------------------------- ### Re.Pcre.get_substring_ofs Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Retrieves the start and end positions (offset) of a captured group within the original string. This is equivalent to `Core.Group.offset`. ```APIDOC ## Re.Pcre.get_substring_ofs Get the start and end positions of a group (equivalent to `Core.Group.offset`). ### Parameters - **groups** (`groups`): The result of a regex execution. - **index** (`int`): The index of the group to retrieve (0 for the full match). ### Returns `int * int` — A tuple containing the start and end offsets of the specified group. ``` -------------------------------- ### Anchor Patterns Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Match positions within the string, such as the start or end of the string/line/word, with options to respect specific positions or lengths. ```ocaml Re.bos (* Start of string (absolute) *) Re.eos (* End of string (absolute) *) Re.start (* Start of string (respects ~pos) *) Re.stop (* End of string (respects ~len) *) Re.bol (* Start of line *) Re.eol (* End of line *) Re.bow (* Start of word *) Re.eow (* End of word *) ``` -------------------------------- ### Get Matched Substring Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Retrieves the substring that was matched by the most recent matching operation. The original string must be passed as an argument. ```ocaml let regex = Re.Str.regexp "[a-z]+" let _ = Re.Str.search_forward regex "123 hello" 0 let text = Re.Str.matched_string "123 hello" (* "hello" *) ``` -------------------------------- ### str Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Creates a literal string pattern that matches exactly the given string. ```APIDOC ## str ### Description Creates a literal string pattern that matches exactly. ### Signature `str : string -> t` ### Parameters * `string`: The literal string to match. ### Returns A pattern `t` that matches the literal string. ``` -------------------------------- ### Split Operation with Zero-Width Pattern Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/README.md Demonstrates the behavior of Re.split with a zero-width pattern like Re.eol, showing how newlines are included in the resulting list. ```ocaml Re.split (Re.compile Re.eol) "a\nb" (* ["a"; "\nb"] — newline is included! *) ``` -------------------------------- ### split_full Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Splits a string and returns both text and delimiter tokens, useful for whitespace-aware splitting. Supports specifying start position and length. ```APIDOC ## split_full ### Description Splits a string and returns both text and delimiter tokens, useful for whitespace-aware splitting. Supports specifying start position and length. ### Method `split_full : ?pos:int -> ?len:int -> re -> string -> split_token list` ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position (default: 0) - **len** (int) - Optional - Length of substring to search (default: -1) - **re** (re) - Required - Compiled regular expression (the delimiter) - **string** (string) - Required - String to split ### Response #### Success Response - **split_token list** - Alternating text and delimiter tokens. ### Request Example ```ocaml let regex = Re.compile (Re.char ',') Re.split_full regex "Re,Ocaml,Jerome" (* [`Text "Re"; `Delim ; `Text "Ocaml"; `Delim ; `Text "Jerome"] *) ``` ``` -------------------------------- ### Perform Case-Insensitive Matching Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/README.md Demonstrates how to perform case-insensitive regular expression matching using different backends: Perl, POSIX, and Core builders. ```ocaml (* Using Perl *) let regex = Re.Perl.compile_pat ~opts:[`Caseless] "hello" (* Using Posix *) let regex = Re.Posix.compile_pat ~opts:[`ICase] "hello" (* Using Core builders *) let regex = Re.compile (Re.no_case (Re.str "hello")) ``` -------------------------------- ### Project File Structure Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/INDEX.md This snippet shows the directory structure of the ocaml-re project, indicating the purpose of each markdown file. ```text output/ ├─ README.md (Start here) ├─ INDEX.md (This file) ├─ 01-core-api.md (Core functions) ├─ 02-perl-posix-emacs.md (Syntax parsers) ├─ 03-glob-pcre-str.md (Compatibility) ├─ 04-replace-and-utilities.md (Utilities) ├─ 05-types.md (Type reference) ├─ 06-quick-reference.md (Cheat sheet) └─ 07-module-index.md (Module catalog) ``` -------------------------------- ### OCaml Re DFA Compilation Performance Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Demonstrates the performance difference between the first match (which builds the DFA) and subsequent matches against the same compiled regex pattern. ```ocaml let regex = Re.Posix.compile_pat "[a-z]+" let _ = Re.exec regex "hello" let _ = Re.exec regex "world" ``` -------------------------------- ### OCaml Re Handling Match Not Found Errors Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Illustrates different methods for handling cases where a regex does not match the input string, including using exceptions, options, and boolean checks. ```ocaml let regex = Re.compile (Re.digit) try let groups = Re.exec regex "hello" with Not_found -> printf "No match" match Re.exec_opt regex "hello" with | Some groups -> printf "Matched" | None -> printf "No match" if Re.execp regex "123" then printf "Matched" ``` -------------------------------- ### exec_opt Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Similar to `exec`, this function searches for the earliest match but returns an `option` type (`Some groups` on match, `None` otherwise) instead of raising an exception. This provides a safer way to handle potential non-matches. Optional `pos` and `len` parameters control the search range. ```APIDOC ## exec_opt : ?pos:int -> ?len:int -> re -> string -> Group.t option ### Description Like `exec` but returns an option instead of raising an exception. ### Method OCaml function call ### Parameters #### Path Parameters - **pos** (int) - Optional - Starting position in the string - **len** (int) - Optional - Length of substring to search (-1 = until end) - **re** (re) - Required - Compiled regular expression - **string** (string) - Required - String to search ### Returns `Group.t option` — `Some groups` if match found, `None` otherwise. ### Example ```ocaml let regex = Re.compile Re.(seq [str "//"; rep print]) match Re.exec_opt regex "# a comment" with | Some groups -> printf "Matched" | None -> printf "No match" ``` ``` -------------------------------- ### Basic Regex Matching Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Perform basic regular expression matching. `exec` raises `Not_found` on no match, while `exec_opt` returns an option. ```ocaml let regex = Re.compile pattern let groups = Re.exec regex "hello" (* Raises Not_found *) let groups_opt = Re.exec_opt regex "hello" (* Returns option *) let matches = Re.execp regex "hello" (* Returns bool *) ``` -------------------------------- ### Validate Email and URL Formats Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/README.md Use compiled POSIX patterns to efficiently validate email addresses and URLs. Subsequent checks are very fast after initial compilation. ```ocaml let email_pattern = Re.Posix.compile_pat "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" let is_valid_email s = Re.execp email_pattern s let url_pattern = Re.Posix.compile_pat "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" let is_valid_url s = Re.execp url_pattern s ``` -------------------------------- ### OCaml Email Regex with Subgroups Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Constructs a regular expression to match email addresses, capturing the username, domain, and top-level domain in separate groups. Requires the RE library. ```ocaml let email = Re.(seq [ group (rep1 (set "a-zA-Z0-9._%+- ")); char '@'; group (rep1 (set "a-zA-Z0-9.- ")); char '.'; group (rep1 (rg 'a' 'z')) ]) ``` -------------------------------- ### OCaml View Character Set Type Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Defines the opaque `View.Cset.t` type representing a character set. Use `View.Cset.view` to get a list of character ranges. ```ocaml type t ``` -------------------------------- ### Match Any Character in a String Set in OCaml Re Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Re.set` to create a pattern that matches any single character present in the provided string. This example matches any vowel. ```ocaml Re.set "aeiou" (* Matches any vowel *) ``` -------------------------------- ### PCRE Compatibility Quick Functions Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md These functions provide PCRE-like regex operations. Use `pmatch` for boolean checks, `extract` for capturing groups, `split` for splitting strings, and `full_split` to include delimiters. ```ocaml let regex = Re.Pcre.regexp "[a-z]+" Re.Pcre.pmatch ~rex:regex "hello" (* Boolean *) let groups = Re.Pcre.extract ~rex:regex "hello" (* String array *) Re.Pcre.split ~rex:regex "a, b, c" (* Split *) Re.Pcre.full_split ~rex:regex "a, b" (* Split with delims *) Re.Pcre.substitute ~rex:regex ~subst:String.uppercase_ascii "hello" ``` -------------------------------- ### Splitting Strings with Regex Delimiters Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/05-types.md Shows how to split a string using a regular expression as a delimiter. The `split_full` function returns a list of alternating text segments and delimiter matches, useful for tokenizing input. ```ocaml let regex = Re.compile (Re.char ',') let tokens = Re.split_full regex "a,b,c" let process = function | `Text s -> printf "text: %s\n" s | `Delim g -> printf "delimiter at %s\n" (Re.Group.get g 0) List.iter process tokens ``` -------------------------------- ### `set : string -> t` Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Creates a character set that matches any single character present in the provided string. ```APIDOC ## `set : string -> t` ### Description Creates a character set that matches any single character present in the provided string. ### Parameters #### Path Parameters - **chars** (string) - Required - String containing characters to match ``` -------------------------------- ### Define a Named Group in OCaml Re Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Re.group` to capture a subgroup within a regular expression. This example creates a named group 'first' that matches the literal string 'a'. ```ocaml Re.group ~name:"first" (Re.str "a") ``` -------------------------------- ### Parse POSIX ERE and Execute Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/02-perl-posix-emacs.md Parses a POSIX ERE string into an abstract pattern, compiles it, and then executes it against an input string. Use this for direct regex matching with POSIX ERE syntax. ```ocaml let pattern = Re.Posix.re "^[a-z]+$" let regex = Re.compile pattern let b = Re.execp regex "hello" (* true *) ``` -------------------------------- ### Re.Pcre.exec Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Executes a compiled regular expression on a given string to find matches and capture groups. It can optionally specify a starting position for the search. Raises `Not_found` if no match is found. ```APIDOC ## Re.Pcre.exec Executes the regex on a string, returning captured groups. ### Parameters - **rex** (`regexp`, required, named): Compiled regex. - **pos** (`int`, optional, default `0`): Starting position. - **string** (`string`, required, positional): String to match. ### Returns `groups` — Match information (alias for `Core.Group.t`). ### Raises `Not_found` — If no match. ### Example ```ocaml let regex = Re.Pcre.regexp "[a-z]+" let groups = Re.Pcre.exec ~rex:regex "hello123" let text = Re.Pcre.get_substring groups 0 (* "hello" *) ``` ``` -------------------------------- ### POSIX-compatible Email Regex Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Compiles a POSIX-style regular expression pattern for matching email addresses. ```ocaml Re.Posix.compile_pat "[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" ``` -------------------------------- ### Re.Group: Group Access Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/07-module-index.md Provides functions to extract information from matched groups in a regular expression. This includes retrieving group text, their start and end positions, and testing for their existence. ```APIDOC ## Re.Group: Group Access Functions for extracting information from matched groups. ### Functions | Function | Type | Purpose | |----------|------|---------| | `get` | `t -> int -> string` | Get group text | | `get_opt` | `t -> int -> string option` | Optional get | | `offset` | `t -> int -> int * int` | Get positions | | `offset_opt` | `t -> int -> (int * int) option` | Optional positions | | `start` | `t -> int -> int` | Start position | | `start_opt` | `t -> int -> int option` | Optional start | | `stop` | `t -> int -> int` | End position | | `stop_opt` | `t -> int -> int option` | Optional end | | `all` | `t -> string array` | All groups | | `all_offset` | `t -> (int * int) array` | All positions | | `test` | `t -> int -> bool` | Test if matched | | `nb_groups` | `t -> int` | Group count | | `pp` | `Format.formatter -> t -> unit` | Pretty-print | ``` -------------------------------- ### repn Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Creates a pattern for bounded repetitions: at least `min` times, and at most `max` times. ```APIDOC ## repn ### Description Bounded repetitions: at least `min` times, at most `max` times. ### Signature `repn : t -> int -> int option -> t` ### Parameters * `pattern` (t): The pattern to repeat. * `min` (int): The minimum number of occurrences. * `max` (int option): The maximum number of occurrences. `None` means unbounded. ### Returns A pattern `t` that matches the specified number of repetitions. ``` -------------------------------- ### Execute PCRE Regex and Get Substrings Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/03-glob-pcre-str.md Executes a compiled PCRE regex on a string and retrieves captured substrings by group index. Ensure the regex is compiled using Re.Pcre.regexp. ```ocaml let regex = Re.Pcre.regexp "[a-z]+" let groups = Re.Pcre.exec ~rex:regex "hello123" let text = Re.Pcre.get_substring groups 0 (* "hello" *) ``` -------------------------------- ### Find All Matches in a String Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Use `Re.matches` to get a list of all substrings that match the regex pattern. For patterns with capturing groups, `Re.all` returns a list of group objects for each match. ```ocaml let regex = Re.Glob.glob "*.ml" let files = Re.matches regex "module.ml lib.ml test.ml config.txt" (* ["module.ml"; "lib.ml"; "test.ml"] *) (* With groups *) let regex = Re.Posix.compile_pat "([a-z]+)=([0-9]+)" let pairs = Re.all regex "x=1 y=2 z=3" List.iter (fun group -> printf "%s = %s\n" (Re.Group.get group 1) (Re.Group.get group 2) ) pairs ``` -------------------------------- ### Re.Core: Core API Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/07-module-index.md The Re.Core module provides the central API for pattern construction, compilation, and matching. It includes functions for building patterns from literals, characters, sequences, and alternations, as well as defining character classes, anchors, and semantic modifiers. ```APIDOC ## Re.Core: Core API ### Description Central module for pattern construction, compilation, and matching. ### Key Types - `t`: Abstract pattern (result of builders) - `re`: Compiled regex (result of `compile`) - `split_token`: Token from split operations ### Pattern Building Functions - `str`: Literal string - `char`: Single character - `seq`: Concatenation - `alt`: Alternation (OR) - `empty`: Matches nothing - `epsilon`: Empty string match - `rep`: 0+ repetitions - `rep1`: 1+ repetitions - `repn`: Bounded repetitions - `opt`: 0-1 occurrences ### Character Classes - `any`: Any character - `notnl`: Not newline - `digit`: 0-9 - `alpha`: a-z A-Z - `alnum`: Alphanumeric - `word`: Word pattern - `space`: Whitespace - `blank`: Space/tab - `upper`: A-Z - `lower`: a-z - `xdigit`: 0-9a-fA-F - `punct`: Punctuation ### Anchors - `bos`: Begin of string (absolute) - `eos`: End of string (absolute) - `start`: Begin (respects pos) - `stop`: End (respects len) - `bol`: Begin of line - `eol`: End of line - `bow`: Begin of word - `eow`: End of word - `leol`: Last EOL or EOS ### Semantic Modifiers - `longest`: Longest-match semantics - `shortest`: Shortest-match semantics - `first`: First-branch preference - `greedy`: Greedy repetition - `non_greedy`: Non-greedy repetition - `no_case`: Case-insensitive - `case`: Case-sensitive ### Groups and Marks - `group`: Capture group - `no_group`: Remove groups - `nest`: Only last match captured - `mark`: Add mark for tracking ### Character Sets - `set`: Characters in string - `rg`: Character range - `inter`: Set intersection - `diff`: Set difference - `compl`: Set complement ### Compilation - `compile`: Compile pattern (`t -> re`) - `group_count`: Get group count (`re -> int`) - `group_names`: Get named groups (`re -> (string * int) list`) ### Execution - `exec`: Match with groups (`Group.t`) - `exec_opt`: Match optional (`Group.t option`) - `execp`: Test match (`bool`) - `exec_partial`: Match with status (`` [`Full | `Partial | `Mismatch] ``) - `exec_partial_detailed`: Match with details (`` [`Full of Group.t | `Partial of int | `Mismatch] ``) ### Batch Operations - `all`: All matches (`Group.t list`) - `matches`: Match strings (`string list`) - `split`: Split, no delims (`string list`) - `split_delim`: Split with empties (`string list`) - `split_full`: Split with delims (`split_token list`) ### Submodules - `Group`: Access matched groups - `Mark`: Track marks in matches - `Seq`: Lazy sequence variants - `Stream`: Streaming matcher ``` -------------------------------- ### Handle Partial Regex Matches for Streaming Input Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Use `Re.exec_partial_detailed` to analyze matches that might be incomplete, returning `Full` for a complete match, `Partial` with a position to extend from, or `Mismatch` if no match is possible. ```ocaml let regex = Re.compile Re.(seq [bos; str "hello"; space; word (rep alpha)]) match Re.exec_partial_detailed regex "hello wor" with | `Full groups -> printf "Complete match" | `Partial pos -> printf "Could extend from position %d" pos | `Mismatch -> printf "No match possible" ``` -------------------------------- ### Match Character Range in OCaml Re Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Re.rg` to define a pattern that matches any single character within a specified range (inclusive). This example matches any lowercase letter from 'a' to 'z'. ```ocaml Re.rg 'a' 'z' (* Matches any lowercase letter *) ``` -------------------------------- ### Re.Core: Execute Partial Match Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/07-module-index.md Executes a compiled regex and returns detailed information about the match status. `exec_partial` indicates full, partial, or mismatch, while `exec_partial_detailed` provides more specific information including group details for partial matches. ```ocaml exec_partial : [`Full | `Partial | `Mismatch] exec_partial_detailed : [`Full of Group.t | `Partial of int | `Mismatch] ``` -------------------------------- ### Find Configuration Value using OCaml Re Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/04-replace-and-utilities.md Extracts a specific value associated with a key from a configuration string. It uses POSIX-style regex compilation with multiline option and captures the value part. ```ocaml let config = "timeout=30\nmax_retries=5\ndebug=true" let find_value key = let pattern = Re.Posix.compile_pat (Printf.sprintf "^%s=(.*)$" (Re.Pcre.quote key)) ~opts:[`Multiline] in match Re.exec_opt pattern config with | Some g -> Some (Re.Group.get g 1) | None -> None find_value "max_retries" (* Some "5" *) ``` -------------------------------- ### Str Module Replacements Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md The `Re.Str` module offers `global_replace` and `replace_first` for direct string replacements, and `global_substitute` which takes a function for replacements. ```ocaml Re.Str.global_replace regex "\\2:\\1" "name value" Re.Str.replace_first regex "X" "hello" Re.Str.global_substitute regex (fun _ -> "X") "hello" ``` -------------------------------- ### Handle Regex Matching Errors with Option Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/README.md Use `Re.exec_opt` and a match statement to safely handle cases where a regular expression might not find a match in the input string. ```ocaml match Re.exec_opt regex "hello" with | Some g -> printf "Matched" | None -> printf "No match" ``` -------------------------------- ### Get Named Capture Group Names and Indices Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Retrieves a list of all named capture groups along with their corresponding indices in the compiled regular expression. Useful for accessing captured groups by name. ```ocaml let regex = Re.compile Re.(seq [ group ~name:"first" (str "a"); group ~name:"second" (str "b") ]) let names = Re.group_names regex (* [("first", 1); ("second", 2)] *) ``` -------------------------------- ### Get Capture Group Count Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Returns the total number of capture groups in a compiled regex, including the implicit group 0 for the whole match. Useful for understanding the structure of captured data. ```ocaml let regex = Re.compile Re.(seq [group (str "a"); group (str "b")]) let count = Re.group_count regex (* Returns 3: group 0, 1, 2 *) ``` -------------------------------- ### Compile Glob Patterns Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/06-quick-reference.md Compile glob patterns for matching file paths. Supports standard and double asterisk wildcards. ```ocaml let regex = Re.Glob.glob "*.ml" let regex = Re.Glob.glob "src/**/*.ml" ~double_asterisk:true let regex = Re.Glob.glob "**" ~pathname:false (* Match anything *) ``` -------------------------------- ### `group : ?name:string -> t -> t` Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Captures a subgroup within a regular expression pattern. Group 0 represents the entire match, and explicit groups are numbered starting from 1. An optional name can be provided for the group. ```APIDOC ## `group : ?name:string -> t -> t` ### Description Captures a subgroup within a regular expression pattern. Group 0 represents the entire match, and explicit groups are numbered starting from 1. An optional name can be provided for the group. ### Parameters #### Path Parameters - **name** (string) - Optional - Optional name for the group - **pattern** (t) - Required - Pattern to group ### Request Example ```ocaml Re.group ~name:"first" (Re.str "a") ``` ``` -------------------------------- ### Matching Functions Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/07-module-index.md Functions for testing and searching for patterns within strings. Includes options for matching from a specific position and retrieving match details. ```APIDOC ## Matching ### `string_match` Test if a regular expression matches a string starting from a given position. - **Signature**: `regexp -> string -> int -> bool` ### `search_forward` Find the first occurrence of a regular expression in a string, searching forward from a given position. - **Signature**: `regexp -> string -> int -> int` ### `search_backward` Find the first occurrence of a regular expression in a string, searching backward from a given position. - **Signature**: `regexp -> string -> int -> int` ### `string_partial_match` Test if a string starts with a pattern from a given position. - **Signature**: `regexp -> string -> int -> bool` ### `matched_string` Retrieve the text of the last successful match. - **Signature**: `string -> string` ### `match_beginning` Get the starting index of the last successful match. - **Signature**: `unit -> int` ### `match_end` Get the ending index of the last successful match. - **Signature**: `unit -> int` ``` -------------------------------- ### Capture Last Match in Repetition with Nesting in OCaml Re Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Use `Re.nest` to ensure only the last match within a repetition is captured. This example demonstrates capturing the last matched character ('a' or 'b') in a repeated sequence. ```ocaml let re = Re.compile (Re.rep1 (Re.nest (Re.alt [Re.group (Re.str "a"); Re.str "b"]))) let group = Re.exec re "ab" Re.Group.get_opt group 1 (* None *) ``` -------------------------------- ### Literal String Pattern Source: https://github.com/ocaml/ocaml-re/blob/master/_autodocs/01-core-api.md Create a pattern that matches an exact string literal. ```ocaml Re.str "hello" (* Matches the exact string "hello" *) ```