Regex Module
Compiled regular expression patterns for matching, searching, replacing, and splitting strings.
Functions
Regex.captures
Regex -> String -> Maybe [Maybe String]
Return the capture groups from the first match of a regex.
import Regex
import Result
case Regex.compile "([0-9]{4})-([0-9]{2})-([0-9]{2})" of
Ok r -> Regex.captures r "2024-01-15"
Err _ -> Nothing
-- Just [Just "2024", Just "01", Just "15"]Try itNotes: Returns Nothing if the pattern does not match. The whole match (group 0) is excluded; only numbered capture groups are returned. Optional groups that did not participate in the match appear as Nothing.
See also: Regex.find, Regex.findAll
Regex.compile
String -> Result Regex String
Compile a regular expression pattern string into a Regex value.
import Regex
import Result
case Regex.compile "[0-9]+" of
Ok r -> Regex.test r "abc123"
Err e -> False
-- TrueTry itNotes: Uses the regex crate syntax. Returns Err with a descriptive message if the pattern is invalid.
See also: Regex.test, Regex.find
Regex.find
Regex -> String -> Maybe String
Find the first match of a regex in the input string.
import Regex
import Result
case Regex.compile "[0-9]+" of
Ok r -> Regex.find r "abc123def456"
Err _ -> Nothing
-- Just "123"Try itSee also: Regex.findAll, Regex.captures
Regex.findAll
Regex -> String -> [String]
Find all non-overlapping matches of a regex in the input string.
import Regex
import Result
case Regex.compile "[0-9]+" of
Ok r -> Regex.findAll r "a1b22c333"
Err _ -> []
-- ["1", "22", "333"]Try itSee also: Regex.find, Regex.captures
Regex.replace
Regex -> String -> String -> String
Replace the first match of a regex in the input string.
import Regex
import Result
case Regex.compile "[0-9]+" of
Ok r -> Regex.replace r "X" "a1b22c333"
Err _ -> "a1b22c333"
-- "aXb22c333"Try itNotes: Only the first match is replaced. Use replaceAll to replace every match.
See also: Regex.replaceAll
Regex.replaceAll
Regex -> String -> String -> String
Replace all non-overlapping matches of a regex in the input string.
import Regex
import Result
case Regex.compile "[0-9]+" of
Ok r -> Regex.replaceAll r "X" "a1b22c333"
Err _ -> "a1b22c333"
-- "aXbXcX"Try itSee also: Regex.replace
Regex.split
Regex -> String -> [String]
Split the input string on all matches of a regex.
import Regex
import Result
case Regex.compile "\\s+" of
Ok r -> Regex.split r "hello world foo"
Err _ -> []
-- ["hello", "world", "foo"]Try itNotes: If the pattern does not match, returns a single-element list containing the whole input.
See also: Regex.findAll
Regex.test
Regex -> String -> Bool
Test whether a compiled regex matches anywhere in the input string.
import Regex
import Result
case Regex.compile "^[0-9]+$" of
Ok r -> Regex.test r "12345"
Err _ -> False
-- TrueTry itSee also: Regex.compile, Regex.find