Skip to content
Logo

Regex output

toPattern(grammar, rule, options) returns a rule's pattern source, and toRegExp compiles the same source with the v flag:

import { , , , ,  } from "@ghostry/aster";
 
const { ,  } = ();
 
const  = ()
  .("digit", () => ("0", "9"))
  .("year", ({  }) => ([, , , ]))
  .("month", ({  }) => ([, ]))
  .("date", ({ ,  }) => ([, ("-"), ]))
  .();
 
(, "date"); // "^[0-9][0-9][0-9][0-9]-[0-9][0-9]$"
(, "date"); // /^[0-9][0-9][0-9][0-9]-[0-9][0-9]$/v

Both run the safety check first, and throw VulnerablePatternError rather than return a slow pattern.

Anchoring

Patterns are anchored by default, ^…$, so they match whole strings, as the parser does. That's also what a JSON Schema pattern needs: JSON Schema doesn't anchor pattern itself, so an unanchored one accepts any string that merely contains a match.

To search inside a longer string, pass { anchored: false }:

toPattern(date, "date", { anchored: false }); // "[0-9][0-9][0-9][0-9]-[0-9][0-9]"

A search retries at every offset, so it can be slower than the anchored pattern, and the safety check accounts for that.

Flags

toRegExp compiles with v. The source toPattern returns also means the same under u, so it works as written in a JSON Schema validator that compiles with u, or in any engine without v. Every character that needs escaping is escaped in a way both flags read the same.

No capturing groups

Patterns use only non-capturing (?:…) groups. Reading the structure is the parser's job, and a capture group inside a loop would keep only its last iteration anyway.

Shape and size

Patterns are written with as few groups as their precedence needs. An either whose alternatives are all single characters becomes one character class, so either(range("a", "z"), range("0", "9")) is [0-9a-z]. repeat with bounds is written as a counted quantifier, {1,3}.

JS regex can't call a subpattern, so every reference is written out in full where it's used. A rule referenced many times is repeated in the pattern each time. Realistic grammars stay small: an IPv4 address is about 220 characters, and a full log line with a timestamp, a URI, and a message is about 1,200. A pattern grows with how often rules are reused.