JSV.Helpers.RegexExt (jsv v0.21.0)

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.

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); a match that exhausts the budget is reported as a non-match.

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}"