Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Regular expressions

Calque’s regular-expression engine is a Thompson NFA: matching time stays predictable even for patterns that cause catastrophic backtracking in engines based on recursive backtracking.

Compile a pattern once if it is reused. String/regex/matches? requires the whole input to match, while String/regex/contains? searches for a match anywhere in the input. Both take their text argument last.

; Compile once when a pattern will be reused.
(let identifier (String/regex "^[a-zA-Z_][a-zA-Z0-9_]*$"))

(let candidates ["calque_2" "2calque" "with-dash"])
(let identifiers
  (map
    (lambda text (String/regex/matches? identifier text))
    candidates))

; `contains?` searches anywhere in the text.
(let ticket (String/regex "ticket-[0-9]+"))
(let contains-ticket
  (String/regex/contains? ticket "opened ticket-42 for review"))

; Invalid patterns compile to a value that can be checked safely.
(let invalid (String/regex "a{3}"))

{identifiers {contains-ticket (String/regex/valid? invalid)}}
; {[true false false] {true false}}

Run it from a checkout with:

que examples/demo/05-regex.que --debug

Supported syntax is grouping, alternation (|), *, +, ?, ., ^, $, character classes and ranges, negated classes, and the \\d, \\D, \\w, \\W, \\s, \\S, \\n, \\r, \\t, \\f, and \\v escapes. It is not a PCRE implementation: counted repetition, word boundaries, backreferences, look-around, and hexadecimal escapes are unsupported.

String/regex never throws for invalid pattern syntax. Instead, String/regex/valid? reports false, and the matching predicates return false. This permits dynamic patterns without making malformed input a runtime failure.