Packages

Compile and evaluate regular expressions using Non-deterministic Finite Automata (NFAs).

Current section

Files

Jump to
rexen src rexen.erl
Raw

src/rexen.erl

-module(rexen).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([new/1, compute/2]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(" Compile and evaluate regular expressions using Non-deterministic Finite Automata (NFAs).\n").
-file("src/rexen.gleam", 23).
?DOC(
" Compiles a regular expression string into a Non-deterministic Finite Automaton (NFA).\n"
"\n"
" Takes a regular expression `String` and returns `Ok(NFA)` on success, or `Error(String)` on failure.\n"
" Uses a shunting-yard algorithm to convert from infix to postfix notation\n"
" Uses Thompson's construction to construct the nfa\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" import rexen\n"
"\n"
" case rexen.new(\"ab\") {\n"
" Ok(_) -> io.println(\"All good\")\n"
" Error(err) -> io.println(err)\n"
" }\n"
" ```\n"
).
-spec new(binary()) -> {ok, rexen@nfa@machine:nfa()} | {error, binary()}.
new(Expression) ->
case rexen@grammar:shunt(Expression) of
{error, Err} ->
{error, Err};
{ok, Toks} ->
rexen@nfa@thompson:to_nfa(Toks)
end.
-file("src/rexen.gleam", 47).
?DOC(
" Evaluates whether a given input `String` is matched by the provided Non-deterministic Finite Automaton (NFA).\n"
"\n"
" Takes an NFA and an input string, returning `True` if the input is accepted by the NFA, and `False` otherwise.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" import rexen\n"
"\n"
" let assert Ok(nfa) = rexen.new(\"(ab)*\")\n"
" rexen.compute(nfa, \"ab\") // -> True\n"
" rexen.compute(nfa, \"ababab\") // -> True\n"
" rexen.compute(nfa, \"ababa\") // -> False\n"
" rexen.compute(nfa, \"a\") // -> False\n"
" ```\n"
).
-spec compute(rexen@nfa@machine:nfa(), binary()) -> boolean().
compute(Engine, Input) ->
rexen@nfa@machine:evaluate(Engine, Input).