Skip to content
Jennifer Programming Language

regex - regular expressions

Enable with use regex;. Six functions over string, one match struct. RE2 syntax (Go's regexp package): a subset of PCRE without backreferences or lookahead / lookbehind.

jennifer
use io;
use regex;

if (regex.matches("^[A-Z][a-z]+$", "Hello")) {
    io.printf("looks capitalised\n");
}

Surface

CallReturnsNotes
regex.matches(pattern, s)boolDoes pattern match anywhere in s?
regex.find(pattern, s)regex.MatchFirst match, or a sentinel with start=-1 on no match.
regex.findAll(pattern, s)list of regex.MatchEvery non-overlapping match, left to right. More than 16777216 / (20 + 2 x groups + 6 x named groups) matches (838860 for a group-less pattern; a sixteenth on jennifer-tiny) is an error.
regex.replace(pattern, s, replacement)stringReplace every match. $1, ${name} expand to captured groups. Errors when the result could pass 256 MiB (32 MiB on jennifer-tiny), bounding each $ reference by its match length.
regex.split(pattern, s)list of stringSplit s at every match of pattern. More than 4194304 parts (262144 on jennifer-tiny) is an error.
regex.escape(s)stringEscape metacharacters so s is treated as a literal pattern.

The regex.Match struct

text
def struct regex.Match {
    text as string,                            # the full matched substring
    start as int,                              # rune index where the match starts
    end as int,                                # rune index where the match ends (exclusive)
    groups as list of string,                  # positional captures (index 0 = group 1)
    groupsNamed as map of string to string     # named captures (see below)
};

start and end are rune indices, consistent with slicing ($s[a..b]) and strings.indexOf. Multi-byte characters advance the count by one per rune, not per byte.

No-match sentinel

regex.find on no match returns a Match with start=-1, end=-1, text="", empty groups, empty groupsNamed:

jennifer
def m as regex.Match init regex.find("[0-9]+", "no digits here");
if ($m.start == -1) {
    io.printf("no match\n");
}

Worked examples

Write patterns as raw single-quoted literals ('\d+', not "\\d+"). In a raw string backslashes are literal, so the pattern reads exactly as its RE2 form. The cooked double-quoted form also works with every \ doubled.

Match a whole string

jennifer
if (regex.matches("^[A-Z][a-zA-Z]*$", $name)) {
    # ... $name starts with a capital and has no digits ...
}

Extract with positional groups

jennifer
def m as regex.Match init regex.find('(\d+):(\d+)', "PORT=8080:9090");
if ($m.start >= 0) {
    io.printf("first=%s second=%s\n", $m.groups[0], $m.groups[1]);
}

Extract with named groups

Named groups are addressed by name in groupsNamed and also appear in positional groups (same order as they appear in the pattern):

jennifer
use regex;
use maps;

def m as regex.Match init regex.find(
    "(?P<key>[a-z]+)=(?P<value>[0-9]+)", "port=8080");
if ($m.start >= 0) {
    io.printf("key=%s value=%s\n",
        $m.groupsNamed["key"], $m.groupsNamed["value"]);
}

maps.has($m.groupsNamed, "some_name") returns whether a named group is present without erroring on missing keys.

Iterate every match

jennifer
def all as list of regex.Match init regex.findAll('\d+', "a1 b22 c333");
for (def m in $all) {
    io.printf("%s at %d..%d\n", $m.text, $m.start, $m.end);
}

Replace with group substitution

$1 in the replacement string expands to positional group 1; ${name} expands to a named group. Doubled $$ produces a literal $. Write the replacement as a raw '...' string: in "..." the {...} of ${name} is interpolation. $1x names group 1x (empty); write ${1}x.

jennifer
def r as string init regex.replace('(\d+)', "port 8080", "[$1]");
# $r is "port [8080]"

def r2 as string init regex.replace(
    '(?P<host>[\w.]+):(?P<port>\d+)', "example.com:80",
    'host=${host} port=${port}');
# $r2 is "host=example.com port=80"

Split on a pattern

jennifer
def parts as list of string init regex.split('\s+', "one   two  three");
# $parts is ["one", "two", "three"]

Escape a literal

regex.escape returns a pattern that matches its input verbatim, for building patterns from user input or literals containing metacharacters:

jennifer
def userInput as string init "1+2=(3)";
def pat as string init regex.escape($userInput);
# $pat is '1\+2=\(3\)'
if (regex.matches($pat, "x = 1+2=(3)")) {
    io.printf("found\n");
}

Syntax

Jennifer uses RE2 syntax exactly as Go's regexp package does; full reference: https://github.com/google/re2/wiki/Syntax. The most-used pieces:

PatternMeaning
.Any character except newline (add (?s) for dotall).
^ / $Start / end of line (with (?m)) or of input (without).
\d \w \sDigit / word char / whitespace.
\D \W \STheir complements.
[abc] [a-z]Character class.
[^abc]Negated character class.
a? a* a+0-or-1, 0-or-more, 1-or-more (greedy).
a?? a*?Lazy variants.
a{n,m}Bounded repetition.
`ab`
(...)Grouping and positional capture.
(?:...)Grouping without capture.
(?P<name>...)Named capture.
(?i)Case-insensitive flag.
(?m)Multiline (^ / $ match at line boundaries).
(?s)Dotall (. matches newline).

Not supported by RE2 (compile errors):

  • Backreferences: \1, \k<name>.
  • Lookahead / lookbehind: (?=...), (?!...), (?<=...), (?<!...).
  • Possessive quantifiers: a++.

RE2 omits these so matching stays linear in the input, which makes it safe for untrusted input.

Errors

Every error is positioned at the call site and catchable with try / catch.

CaseKindExample message
Invalid pattern (quoted, escaped, cut after 64 characters, with the RE2 reason)"runtime"regex.find: invalid pattern "x[": missing closing ]: "["
Pattern over 32 KiB, or compiling to more than 50,000 instructions"limit"regex.matches: pattern "x{1000}x{1000}..."... compiles to 62002 instructions, over the limit of 50000
findAll, replace or split result cap"limit"regex.split: more than 4194304 parts
Wrong argument type"runtime"regex.matches: pattern must be string, got int
Wrong argument count"runtime"regex.replace expects 3 arguments (pattern, s, replacement), got 2

Pattern caching

The library keeps an LRU cache of compiled patterns, so a hot loop reusing a pattern string compiles it once. It holds at most 128 patterns and 1048576 compiled instructions in all (131072 on jennifer-tiny); past either, the least recently used patterns are evicted silently.

A pattern that compiles to an excessively large program (a short pattern can expand to millions of instructions through nested bounded repeats) is a catchable error, so the cache stays bounded in memory even under attacker-supplied patterns. The 32 KiB length limit comes first, because measuring a program means parsing and compiling it, which itself costs memory in proportion to the pattern. A compile does not hold the cache lock, so a slow one never stalls other regex calls.

Untrusted patterns

The engine is Go's regexp, pure Go and memory-safe, so a hostile pattern cannot corrupt memory the way the 2026 Onigmo (Ruby) repeat-counter overflow did, and matching never backtracks, so (x+x+)+y stays fast. What a hostile pattern can still cost is time: matching runs in time proportional to the input length times the program size. A pattern near the 50,000-instruction limit takes seconds per 100 KB of input. When users supply patterns (a search box, a rule engine, a schema's pattern), bound the input length too, or run the match in a spawn that can be abandoned.

What's left out

  • regex.compile + regex.Pattern handle. The implicit LRU cache handles the common case.
  • Non-string operations (regex over bytes).
  • Streaming iterator (for (def m in regex.iter(pat, s))).
  • Global-flag arguments. Case-insensitive as a boolean parameter would leak an option that already lives in the pattern ((?i)).
  • regex.count. Write len(regex.findAll(pat, s)).
  • Backreferences, lookahead, lookbehind. RE2 does not support them (the cost of linear-time matching).

See also