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.
Extract, replace, and split matches
Section titled “Extract, replace, and split matches”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 emailall matches of "[0-9]+" in textreplace matches of "[0-9]+" in text with "#"split text by pattern "[,;] *"all matches of "abc" in text ignoring casematches the pattern(ormatches pattern) is a condition: true when the pattern is found anywhere in the text (anchor with^/$for a full match).first match ofreturns a match record withtext,start/end(character offsets),groups(positional captures, null when unmatched), andnamed(named captures via(?P<name>...)) — ornilwhen nothing matches.all matches ofreturns the matched strings;replace matches of ... withreplaces every occurrence ($1/${name}in the replacement refer to captures);split ... by patternsplits on every match.- A trailing
ignoring casemakes 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 Zandsplit X by Yare unchanged: they match literal text, never patterns.