Skip to content

Pattern Matching

A text pattern describes a family of strings rather than one literal string. For example, an invoice code can be required to contain letters followed by digits. Devlish’s pattern helpers use regular expressions to test text, extract matching parts, or replace them.

These helpers are useful when ordinary text operations are not specific enough. A condition such as code matches the pattern "^[A-Z]{2}-[0-9]+$" belongs in an If or Require statement. The snippets below are value-producing expressions for use after equals, Print, or Respond with.

A first match returns a record with the matched text and captures. All matches returns a list of strings. Replacement and splitting use the pattern to decide which portions of the input to change or separate.

first match of "(?P<user>[a-z]+)@(?P<host>[a-z]+)" in email
all matches of "[0-9]+" in text
replace matches of "[0-9]+" in text with "#"
split text by pattern "[,;] *"
all matches of "abc" in text ignoring case
  • matches the pattern (or matches pattern) is a condition: true when the pattern is found anywhere in the text (anchor with ^/$ for a full match).
  • first match of returns a match record with text, start/end (character offsets), groups (positional captures, null when unmatched), and named (named captures via (?P<name>...)) — or nil when nothing matches.
  • all matches of returns the matched strings; replace matches of ... with replaces every occurrence ($1 / ${name} in the replacement refer to captures); split ... by pattern splits on every match.
  • A trailing ignoring case makes the pattern case-insensitive. Inline flags such as (?im) also work inside the pattern.
  • An invalid pattern written literally is a compile error; an invalid pattern arriving through a variable fails the run loudly.
  • Plain replace X in Y with Z and split X by Y are unchanged: they match literal text, never patterns.