JSV.Helpers.RegexExt (jsv v0.28.3)

Copy Markdown View Source

Helpers to compile and run ECMA-262 regular expressions (the dialect used by JSON Schema pattern and patternProperties) with Erlang's regex engine.

Erlang's :re (PCRE2) accepts Unicode script and binary property names, but rejects the long General_Category names that ECMA-262 allows, such as \p{Letter} or \p{General_Category=Number}. translate_ecma_regex/1 rewrites those into the short codes PCRE2 understands (\p{L}, \p{N}), leaving everything else untouched.

Summary

Functions

Returns whether regex matches subject, like Regex.match?/2, but with a backtracking budget proportional to the subject size.

Compiles an ECMA-262 regular expression with translate_ecma_regex/1 and Unicode semantics. As in ECMA-262, \d, \w and \b only match ASCII characters, while . and property escapes such as \p{L} match Unicode code points.

Rewrites the Unicode property escapes of an ECMA-262 regular expression into the equivalent escapes understood by Erlang's :re engine.

Functions

bounded_match?(regex, subject)

@spec bounded_match?(Regex.t(), binary()) :: boolean()

Returns whether regex matches subject, like Regex.match?/2, but with a backtracking budget proportional to the subject size.

Schema-supplied pattern and patternProperties regexes can require catastrophic backtracking on crafted data. This function bounds the match cost linearly in byte_size(subject). When a match exhausts the budget, the engine could not determine whether the subject matches, and {JSV.Helpers.RegexExt, :budget_exhausted} is thrown.

compile_ecma_regex(ecma_regex)

@spec compile_ecma_regex(binary()) :: {:ok, Regex.t()} | {:error, term()}

Compiles an ECMA-262 regular expression with translate_ecma_regex/1 and Unicode semantics. As in ECMA-262, \d, \w and \b only match ASCII characters, while . and property escapes such as \p{L} match Unicode code points.

The ASCII-only \d, \w and \b need OTP 28 or later (PCRE2 10.43). On older versions they match Unicode characters too.

Examples

iex> {:ok, re} = JSV.Helpers.RegexExt.compile_ecma_regex("^\\d+$")
iex> {Regex.match?(re, "42"), Regex.match?(re, "٤٢")}
{true, false}

translate_ecma_regex(ecma_regex)

@spec translate_ecma_regex(binary()) :: binary()

Rewrites the Unicode property escapes of an ECMA-262 regular expression into the equivalent escapes understood by Erlang's :re engine.

Examples

iex> JSV.Helpers.RegexExt.translate_ecma_regex("^\\p{Letter}+$")
"^\\p{L}+$"

iex> JSV.Helpers.RegexExt.translate_ecma_regex("\\p{General_Category=Number}")
"\\p{N}"

iex> JSV.Helpers.RegexExt.translate_ecma_regex("\\p{Latin}")
"\\p{Latin}"