Regex match expressions#

The regex match operators ~ and !~ and the /pattern/flags literal syntax. Regex is the language's only string-matching mechanism beyond equality (== / !=); no starts_with / ends_with / contains predicates exist.

The capture profile of the pattern determines the legal position: capture-bearing patterns bind in a where clause with a binding form, capture-free patterns gate in a where without one, and both gate ([LREG.4.6]). The compiler enforces the position rule.

Paired with:

  • [LLEX] for regex literal lexing.

  • [LSTR] for the codepoint-level Unicode contract regex operates against.

  • [LGRA] for let and where clause positions.

  • [LEXP] for the broader expression surface.

What this is not#

  • Not a regex tutorial. The pattern syntax is RE2's; authors consult RE2 documentation for pattern features.

  • Not a string-operations library. Substring extraction, replacement, splitting belong elsewhere.

  • Not a where-predicate library. The only string predicates in where are ==, !=, ~, and !~.


Match operators [LREG.1]#

[LREG.1.1] The expression language must accept two binary operators: ~ (match) and !~ (negated match). Both take a String-typed expression on the left and a regex literal on the right.

ratified

[LREG.1.2] s ~ /pattern/ evaluates the pattern against the codepoint sequence of s. In its plain form ([LREG.2.1]) the expression is a Boolean test: a where holding it passes on a match and fails, rejecting the activation silently, on no match.

ratified — see also: LREG.2.1

[LREG.1.3] s !~ /pattern/ is the negated dual: the activation continues iff the pattern does not match s. By definition no captures arise from a non-match; !~ produces no bindings. A null s does not fail to match: it propagates, and the activation does not continue ([LNUL.4.1]).

ratified — see also: LNUL.4.1

[LREG.1.4] Both operators bind tighter than logical operators and looser than postfix operators (full precedence rules in [LEXP]). Authors writing s1 ~ /a/ and s2 ~ /b/ get the two-test reading without parentheses.


Position rule [LREG.2]#

[LREG.2.1] Every match expression is legal in where only, never in let ([LREG.4.1]). The capture profile of its pattern determines which where form it must use:

Pattern shape

Required where form

One or more capturing groups

the capture-binding form, where (name, ...) = ...

Zero capturing groups

the plain boolean form, where ... ~ /pattern/

Negated (!~)

the plain boolean form

The compiler must reject a ~ match expression on a let's right-hand side, whatever its capture profile, as DS_VALIDATE_REGEX_CAPTURE_IN_LET, with a message that points the author at the where form the table names. A !~ there is [LREG.2.5]'s refusal instead.

ratified — see also: LREG.2.5, LREG.4.1

[LREG.2.2] DS_VALIDATE_REGEX_LET_NO_CAPTURES and DS_VALIDATE_REGEX_LET_TUPLE_FORM are reserved allocations, out of use ([STYL.2.8.7]). specs/registry/validate.ebnf keeps both as non-alternation productions, and a compiler must not raise either. A match in let position is [LREG.2.1]'s DS_VALIDATE_REGEX_CAPTURE_IN_LET.

ratified — see also: LREG.2.1

[LREG.2.3] A plain boolean where clause — one with no capture-binding prefix ([LREG.4.1]) — containing a ~ expression must use a pattern of zero capturing groups. The compiler must reject a plain boolean where whose pattern has captures with a message that names the offending pattern and points the author at converting the captures to non-capturing groups ((?:...)) or binding them with the capture-binding where form.

ratified — see also: LREG.4.1

[LREG.2.4] A where clause containing !~ must use a pattern of zero capturing groups; capture-bearing !~ patterns are a compile error (DS_VALIDATE_REGEX_WHERE_HAS_CAPTURES). The error message names the patterns and asks the author to remove the captures.

ratified

[LREG.2.5] !~ is not legal in let. A let binding whose right-hand-side is a !~ expression is a compile error ("!~ produces no captures; use where s !~ /pattern/").


ratified

Captures [LREG.3]#

[LREG.3.1] A pattern's parentheses fall into three states:

Form

Captures?

Binding

(?<name>...)

yes

named, position-bound, name must match the binding-form slot at that position

(...)

yes

positional, the binding-form slot at that position takes the author's chosen identifier

(?:...)

no

grouping only; absent from the binding form

[LREG.3.2] Bare (...) (without ?<name> or ?:) is a positional capturing group. Authors who need grouping without a binding must use (?:...).

ratified

[LREG.3.3] The compiler must reject a (?<name>...) capture whose name does not match the binding-form name at the same position. The error names both the pattern's capture name and the binding form's name.


ratified

Binding form [LREG.4]#

[LREG.4.1] The binding form for a capture-bearing match is a parenthesised, comma-separated, positional list of identifiers, and it attaches to a where clause. An ordinary predicate may follow it on the same clause, and may reference the captures ([LGRA.8.1]).

The capture form is a where form, and only a where form. A capture must not be written as a let: a let is RHS-only ([LLET]), so it is evaluated after the rule has fired, and there is no answer to what a capture is worth when the pattern did not match.

In where, the question does not arise. A non-matching pattern is a pattern that does not match: no activation is created, and there is no binding to give a value to. That is why [LREG.4.4] can say the captured values are String rather than String?.

ratified — see also: LGRA.8.1, LREG.4.4

[LREG.4.2] The number of binding-form names must equal the number of capturing groups (named or positional) in the pattern. The compiler must reject mismatches.

ratified

[LREG.4.3] No {name, name} destructuring shape is admitted. The binding form is paren-delimited; one shape across the language.

[LREG.4.4] Captured values are String per [LSTR.1] regardless of pattern shape. (?<count>\d+) captures the digit codepoints as a String; the author converts to numeric via s::Int? ([LCST.4.5.7]) when needed. Regex engines do not infer types.

ratified — see also: LCST.4.5.7, LSTR.1

[LREG.4.5] An operand of ~ or !~ whose type is not String is a compile error. Json-typed operands require an explicit projection to String first; a type mismatch at a Json leaf raises a TypeError per [LEXP.7.12].


ratified — see also: LEXP.7.12

[LREG.4.6] A capture-bearing match is part of the LHS, and the capture profile does not decide the position. A capture-bearing ~ appears in a where clause with a binding form ([LREG.4.1]); a capture-free ~ appears in a where clause without one. Both gate. !~ remains capture-free ([LREG.2.4]) — a match that must not happen has nothing to bind.

One where is enough to both gate and capture. An author who needs both writes one clause rather than two kept in step by hand — [LDIA.4.1] states the cost such duplication would carry in three words: a second copy is what drifts.

The captures are ordinary bindings from the moment they are bound. They follow [LGRA.8.6]'s scope ladder exactly as a pattern binding does — referenceable in this pattern's own where, in a later pattern's where, in a let right-hand side, and in an action — and a capture that is never referenced is the same compile error a never-referenced pattern binding is. That last part is not incidental: it is what catches a mistyped capture name, since the misspelling is the binding nothing refers to.

Reaching a later pattern's where is the capability this buys, not a side effect. Event e where (dev) = e.msg ~ /(?<dev>\w+)/ followed by Device d where d.id == dev is a join on a captured value, expressible without an intermediate fact. It is a legal join test under [LEXP.9.6.1] because a capture is a function of the matched fact and the pattern — it reads no state the network does not track.

see also: LDIA.4.1, LEXP.9.6.1, LGRA.8.6, LREG.2.4, LREG.4.1

[LREG.4.7] A capture is a function of the matched fact and the pattern alone, so how many times an implementation evaluates it is not observable. An engine may compute a capture once and carry the result, or re-derive it wherever the value is used, or both in one artefact. No program can tell the difference, so this document does not choose.

This is why the clause is about purity and not about caching. It is the same rule [RDSC.5a.1a] applies to aggregation reads, run in the opposite direction: there, a read must not mutate state, because the number of reads is unfixed under any evaluation strategy and a non-idempotent read would make the answer depend on how many rules referenced it. Here the idempotence is free — RE2 is deterministic and the fact is immutable while matched — and what it buys back is the engine's choice.

What that choice costs is worth knowing before it surprises someone. The single-pattern case is free: the test and the fire happen in one pass, so the match is already in hand. A join is where re-derivation is reached, because the capture is needed when the other side arrives, and it is paid per candidate fact examined rather than once per join — a constant factor on work the join already does, not a new complexity class. An engine that carries the value instead pays storage rather than time. Both conform.

Under realtime the cost lands where the contract already accounts for it. Re-matching is bounded because RE2 is linear by construction ([LREG.7.1]) — it is the reason that engine is mandated rather than a convenience — so the work is pump work under pump_wcet_ns ([RTCT.7.1]) rather than an unbounded allocation. An engine that carries the value instead consumes the intern table, which intern_cap and intern_bytes_cap already bound. Neither strategy needs a cap that does not exist.

see also: LREG.7.1, RDSC.5a.1a, RTCT.7.1

[LREG.4.8] Whether a capture may be a join key under linear_scan: false is not settled here, and is not settled by analogy. linear_scan: false buys O(1) joins by requiring every join be anchored on a logical identity slot with J_max = 1 provable ([LNLS]). A capture is not a slot — it is derived from one — so the anchor argument does not reach it as written, and the shape that makes linear_scan: false sound is exactly the shape a captured join key sits outside.

The obvious ruling is that a capture-anchored join is inadmissible in that dialect, and it is deliberately not being made. The two are not obviously equivalent to measurement: an anchor's job is to bound fan-out, and a capture over an identity-derived field may or may not bound it as tightly as the slot itself. That is an empirical question about the shapes real programs compile to, and answering it from the armchair would either forbid something the dialect can support or admit something it cannot bound — and linear_scan: false's whole value is that its guarantee is provable rather than hoped for.

Until it is measured, a linear_scan: false compiler must refuse a capture used as a join key — a pattern whose anchor ([LNLS.3.3]) is complete only when a capture of an earlier pattern stands in for that pattern's key slot — with DS_VALIDATE_NOLINSCAN_CAPTURE_JOIN_KEY, and the refusal must name this clause rather than [LNLS]'s anchor rule, whose refusals are the DS_VALIDATE_NOLINSCAN_JOIN_ANCHOR_* codes — so that a program refused by a conservative default is distinguishable from one refused by a settled prohibition. Every other use of a capture is unaffected in that dialect, including a capture referenced only within its own pattern's where or in an action, neither of which is a join. A capture read in a further constraint on top of a complete anchor is not a join key either ([LNLS.3.3]).

ratified — see also: LNLS.3.3, LREG.4.6

Pattern syntax [LREG.5]#

[LREG.5.1] A regex literal is /<pattern>/<flags>. The pattern is the regex source per the engine class in §LREG.8; the flags are an optional, order-independent set per §LREG.5.2.

ratified — see also: LREG.5.2, LREG.8

[LREG.5.2] Three flags are defined:

Flag

Meaning

i

Case-insensitive matching

m

^ and $ match line boundaries (default: string boundaries)

s

. matches newlines (default: doesn't)

ratified

[LREG.5.3] Flags are an unordered set; /foo/im and /foo/mi are equivalent. The compiler must reject duplicate flags (/foo/ii) as a compile error pointing at the literal.

ratified

[LREG.5.4] Flags outside the set in §LREG.5.2 are a compile error. x and u are reserved; using them is rejected.

see also: LREG.5.2

[LREG.5.5] The pattern must be a literal. Computed patterns (string interpolation, variable references, runtime-built strings) are not legal. The compiler must reject any non-literal right-hand-side of ~ or !~ as a parse error (DS_PARSE_GENERIC).


Lexer rule [LREG.6]#

[LREG.6.1] / is the division operator throughout the language except when it immediately follows ~ or !~ as the next non-whitespace token. In that position, / begins a regex literal that runs until the closing /, optionally followed by flag characters.

ratified

[LREG.6.2] The lexer must use one-token lookback after ~ and !~ to determine whether a following / opens a regex literal or starts a division expression. The rule is local to the two match operators; no full parser-state context-tracking is required.

[LREG.6.3] The character sequence ~ / and !~ / always begins a regex literal. Division expressions on the right of ~ or !~ are not legal; the lexer's regex-literal mode covers the whole tail.

ratified

[LREG.6.4] Backslash escaping inside a regex literal follows RE2 conventions per §LREG.8. A literal / inside a pattern must be written \/. The closing / is the first unescaped / after the opening one.

see also: LREG.8

[LREG.6.5] Newlines inside a regex literal are a lexer error. Patterns that need a newline character use \n.


ratified

Compile-time validation [LREG.7]#

[LREG.7.1] The compiler must parse every regex literal at compile time and reject syntax errors with the literal's source location. RE2 syntax errors surface as DS compile errors; the author does not see RE2's parser output, only a message naming the offending construct.

ratified

[LREG.7.2] The compiler must reject:

  • Capture/binding-form length mismatches per [LREG.4.2].

  • Named-capture / binding-form name mismatches per [LREG.3.3].

  • A capture written outside the where position, or position-rule violations within it, per [LREG.4.1] / [LREG.2.3] / [LREG.2.4] / [LREG.2.5].

  • Type mismatches per [LREG.4.5].

  • Flag duplicates and unknown flags per [LREG.5.3] / [LREG.5.4].

  • Non-literal right-hand-sides per [LREG.5.5].

see also: LREG.2.3, LREG.2.4, LREG.2.5, LREG.3.3, LREG.4.1, LREG.4.2, LREG.4.5, LREG.5.3, LREG.5.4, LREG.5.5

[LREG.7.3] Pattern semantic correctness — whether the pattern matches the strings the author intended — is an authoring concern, not a compile-time check.


Engine [LREG.8]#

[LREG.8.1] The regex syntax is RE2. A pattern means what RE2's published specification says it means. DS defines no dialect of its own, admits no superset, and the choice is a commitment of the language rather than of any particular runtime.

Linear-time evaluation in the input length, and the absence of catastrophic backtracking, follow from RE2. They are consequences of the choice, not an alternative way of satisfying it: an engine exhibiting those properties under a different syntax — POSIX ERE, for instance — is not conforming, because the patterns an author may write would differ. Equally, an engine offering RE2's syntax plus backtracking extensions (PCRE-family) is not conforming, because the linear-time guarantee would no longer hold.

ratified

[LREG.8.2] RE2's specification is the normative source for pattern syntax, and it is not restated here. The feature lists that follow are orientation only: where they and RE2 disagree, RE2 governs. Authors consult RE2's documentation for the definitive surface.

What this document does define normatively is everything RE2 does not: the /pattern/flags literal form, which flags DS admits, the capture profile and the positions it makes legal, and how an unsupported construct is reported at compile time.

[LREG.8.3] The admitted surface is RE2's, entire. [LREG.8.1] admits no superset and no subset, so every construct RE2 accepts is writable in a DS pattern. No list of them is kept here: a hand-maintained copy of another specification's grammar drifts, nothing checks it, and this one had ([STYL.2.15.1]).

What follows is not an enumeration but the residue — the places where a pattern that looks right to an author coming from another engine is not RE2:

  • The Unicode escape is \x{10FFFF}. The \u{HHHH} form is JavaScript and Rust notation; RE2 has never had it.

  • The absolute anchors are \A and \z. \Z is not RE2.

  • (?U) inverts the greediness of every quantifier after it for the remainder of the pattern. It is admitted, and it is the one flag that changes what a pattern matches rather than how it is read — note that it arrives inside the pattern body, not in the literal's flag position ([LREG.5]).

  • (?<name>...) and (?P<name>...) both name a group and reach the same capture; [LREG.3] writes the first.

  • Unicode classes (\pL, \p{Greek}) and POSIX classes ([[:alpha:]]) are admitted, on the same grounds as everything else RE2 accepts.

see also: LREG.8.1, LREG.5, LREG.3

[LREG.8.4] An unsupported construct is a compile error, and the diagnostic names the feature. RE2 refuses backreferences (\1, \k<name>), lookaround ((?=, (?!, (?<=, (?<!), possessive quantifiers (*+, ++, ?+, {n,m}+) and atomic groups ((?>) on its own, so this clause adds no rejection. It adds the two things RE2 cannot:

  • the failure is at compile time, before a bundle exists; and

  • the message is DS's own, naming the construct in the author's terms — "positive lookahead (?=...) is not supported by the RE2-class engine" — rather than surfacing RE2's parse error, invalid perl operator: (?=.

The code is DS_VALIDATE_REGEX_UNSUPPORTED_FEATURE.

A compiler must not be stricter than RE2 either. Refusing a pattern RE2 accepts breaks [LREG.8.1] exactly as admitting a superset would, because the set of patterns an author may write again differs from RE2's. A scan that recognises unsupported constructs must therefore model enough of RE2's grammar not to fire on their spellings elsewhere — inside a character class, [*+] is two literal members, not a possessive quantifier.

Authors needing these features model the value structure upstream (in adapter parsing, a typed schema slot, etc.) rather than at rule time.

ratified — see also: LREG.8.1

[LREG.8.5] Engine semantics for character classes follow RE2's defaults. \w matches [A-Za-z0-9_] (ASCII), not Unicode word characters. A u flag for Unicode-aware classes is reserved per [LREG.5.4]; until it lands, authors needing Unicode word-class semantics enumerate explicitly via character-class brackets.


see also: LREG.5.4

Cost of regex in where [LREG.9]#

[LREG.9.1] A regex test in where is a non-hash-routable predicate. Its alpha-node cost class is the same as range tests on numerics and cross-slot comparisons; one regex evaluation per fact assertion per distinct pattern in scope.

[LREG.9.2] Rete alpha-node sharing applies. Identical patterns across rules share evaluation; the engine evaluates the regex once per fact assertion and the result feeds every rule with that test. Authors writing the same pattern in many rules pay the cost once, not once per rule.

[LREG.9.3] Per-fact regex evaluation cost under RE2 is linear in the input length and bounded regardless of pattern. There is no catastrophic-backtracking surface.

Regex commitments [LREG.10]#

[LREG.10.1] Capture-free regex is legal in where. Per [LREG.2.1]. Capture-free regex shares the alpha-node cost class of every other non-hash-routable predicate already in the language.

ratified — see also: LREG.2.1

[LREG.10.2] Capture-bearing regex is where-only. Per [LREG.4.1]. Captures bind values; binding lives in the where capture-binding form.

ratified — see also: LREG.4.1

[LREG.10.3] !~ is where-only. Per [LREG.2.4] / [LREG.2.5]. Non-match produces no captures by definition; let needs bindings.

ratified — see also: LREG.2.4, LREG.2.5

[LREG.10.4] No throwaway / unused capture bindings. Per [LREG.3.2]. Authors who do not want a slot use (?:...). No underscore convention, no positional placeholder.

ratified — see also: LREG.3.2

[LREG.10.5] Named-capture names must match binding-form names. Per [LREG.3.3]. The pattern is self-documenting; name mismatches are typo bait the compiler catches.

see also: LREG.3.3

[LREG.10.6] Captures are always String. Per [LREG.4.4]. Conversion to numeric or other types is the author's responsibility, with the :: cast ([LCST.4.5.2]).

see also: LCST.4.5.2, LREG.4.4

[LREG.10.7] Patterns are literal. Per [LREG.5.5]. No interpolation, no computed patterns — the compiler validates every pattern at compile time.

ratified — see also: LREG.5.5

[LREG.10.8] Lexer rule is local to ~ and !~. Per [LREG.6]. No full parser-state context-tracking; one-token lookback.

ratified — see also: LREG.6

[LREG.10.9] Three flags: i, m, s. Per [LREG.5.2]. Order-independent set; duplicates rejected; unknown flags rejected.

ratified — see also: LREG.5.2

[LREG.10.10] RE2. Per [LREG.8.1]. Linear-time evaluation, no catastrophic backtracking, no backreferences, no lookaround. The trade is bounded cost for reduced expressiveness.

see also: LREG.8.1

[LREG.10.11] Substring tests are regex. Authors write ~ /^err/, ~ /err$/, ~ /err/.


ratified