Functional Weave
Code in Python

text.pattern-match

Does the whole value match an HTML pattern attribute? The same answer in a browser, Python and Rust.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 47 tests, run in TypeScript, Python and Rust.

What it does

`matchesPattern(pattern, value)` answers what an input's `pattern` attribute answers in the browser: does the **whole** value match? The browser compiles `pattern` as `^(?:pattern)$` with the `v` flag; this does the same, in TypeScript, Python and Rust, so a server checks a submitted form with exactly the rule the browser showed. `form.validate-input` uses it for its `pattern` rule.

matchesPattern("[0-9]{5}", "90210");      // true
matchesPattern("[0-9]{5}", "90210\n");    // false: no trailing-newline slack
matchesPattern("(?=.*\\d).{8,}", "x");    // throws "unsupported pattern: ..."

For example

  • matches_pattern([0-9]{5}, 90210) → true five digits: a US ZIP code matches
  • matches_pattern([0-9]{5}, 9021) → false the whole value must match: four digits of five do not
  • matches_pattern([0-9]{5}, 902101) → false the whole value must match: a sixth digit is not ignored

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def matches_pattern(pattern: str, value: str) -> bool
patternstringa regular expression in the portable subset the README lists, as an input's pattern attribute takes it
valuestringthe text to test; the pattern must match all of it, as the browser's pattern check does
returnsbooltrue when the whole value matches

Your code names it in one line, in the file that uses it

from fune.text.pattern_match import matches_pattern  # text.pattern-match@^1
impl/python.py · 369 lines · open · raw
# A whole-string matcher for the portable subset of the regular expressions an
# HTML pattern attribute takes. The pattern is compiled to a small program and
# run as a Thompson NFA (a Pike VM without captures), so time is linear in the
# value whatever the pattern: (a+)+b cannot blow up as a backtracking engine
# would. Python's re is not used: its classes, $ and flags answer differently
# from the browser's (see spec/AUTHORING.md, "Same answers in every language").
from typing import List, Optional, Tuple

MAX_PATTERN = 1000
MAX_REPEAT = 1000
MAX_PROGRAM = 20000
MAX_CODE_POINT = 0x10FFFF

DIGIT = [(48, 57)]
WORD = [(48, 57), (65, 90), (95, 95), (97, 122)]
SPACE = [(9, 13), (32, 32)]
# What `.` does not match: the line terminators, as in JavaScript.
LINE_ENDS = [(10, 10), (13, 13), (0x2028, 0x2029)]
SYNTAX = "^$\\.*+?()[]{}|/"
CLASS_SYNTAX = "()[]{}/-\\|"
DOUBLED = "&!#$%*+,.:;<=>?@^`~"
CLASS_PUNCTUATORS = "&-!#%,:;<=>@`~"

CONTROL = {"t": 9, "n": 10, "v": 11, "f": 12, "r": 13}
CLASSES = {"d": (DIGIT, False), "D": (DIGIT, True), "w": (WORD, False), "W": (WORD, True), "s": (SPACE, False), "S": (SPACE, True)}

# A node is (atom, min, max) with max -1 for unbounded; an atom is
# ("class", ranges, negated) or ("group", alternatives).


def _unsupported(detail: str) -> ValueError:
    return ValueError("unsupported pattern: " + detail)


def _is_ascii_digit(c: int) -> bool:
    return 48 <= c <= 57


def _complement(ranges: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
    out = []
    nxt = 0
    for lo, hi in sorted(ranges, key=lambda r: r[0]):
        if lo > nxt:
            out.append((nxt, lo - 1))
        if hi + 1 > nxt:
            nxt = hi + 1
    if nxt <= MAX_CODE_POINT:
        out.append((nxt, MAX_CODE_POINT))
    return out


class _Parser:
    def __init__(self, cps: List[int], end: int, pos: int) -> None:
        self.cps = cps
        self.end = end
        self.pos = pos

    def peek(self) -> Optional[int]:
        return self.cps[self.pos] if self.pos < self.end else None

    def parse_alt(self, depth: int) -> list:
        alt = [self.parse_seq(depth)]
        while self.peek() == 124:  # |
            self.pos += 1
            alt.append(self.parse_seq(depth))
        return alt

    def parse_seq(self, depth: int) -> list:
        seq = []
        while True:
            c = self.peek()
            if c is None or c == 124:
                return seq
            if c == 41:  # )
                if depth == 0:
                    raise _unsupported("unbalanced )")
                return seq
            atom = self.parse_atom(depth)
            lo, hi = self.parse_quantifier()
            seq.append((atom, lo, hi))

    def parse_atom(self, depth: int) -> tuple:
        c = self.cps[self.pos]
        ch = chr(c)
        if ch in "*+?":
            raise _unsupported("nothing to repeat before " + ch)
        if ch == "{":
            if self.read_braces() is not None:
                raise _unsupported("nothing to repeat before {")
            raise _unsupported("a lone { must be escaped as \\{")
        if ch in "}]":
            raise _unsupported("a lone %s must be escaped as \\%s" % (ch, ch))
        if ch == "^":
            raise _unsupported("^ is only supported at the start of the pattern")
        if ch == "$":
            raise _unsupported("$ is only supported at the end of the pattern")
        if ch == ".":
            self.pos += 1
            return ("class", LINE_ENDS, True)
        if ch == "(":
            self.pos += 1
            if self.peek() == 63:  # ?
                if self.pos + 1 < self.end and self.cps[self.pos + 1] == 58:  # :
                    self.pos += 2
                else:
                    raise _unsupported("lookaround, named groups and flags are not supported")
            alt = self.parse_alt(depth + 1)
            if self.peek() != 41:
                raise _unsupported("unbalanced (")
            self.pos += 1
            return ("group", alt)
        if ch == "[":
            return self.parse_class()
        if ch == "\\":
            self.pos += 1
            ranges, negated, _single = self.parse_escape(False)
            return ("class", ranges, negated)
        self.pos += 1
        return ("class", [(c, c)], False)

    def parse_escape(self, in_class: bool) -> tuple:
        # After a backslash: a class escape, a control escape or escaped punctuation.
        c = self.peek()
        if c is None:
            raise _unsupported("the pattern ends with a lone \\")
        self.pos += 1
        ch = chr(c)
        if ch in CLASSES:
            ranges, negated = CLASSES[ch]
            return (ranges, negated, None)
        if ch in CONTROL:
            n = CONTROL[ch]
            return ([(n, n)], False, n)
        # Escaped punctuation: what the v flag accepts, the syntax characters
        # everywhere and the reserved punctuators inside [...].
        if ch in SYNTAX or (in_class and ch in CLASS_PUNCTUATORS):
            return ([(c, c)], False, c)
        raise _unsupported("\\%s is not supported (backreferences, \\b, \\p, \\u and \\x are not)" % ch)

    def parse_class(self) -> tuple:
        self.pos += 1  # [
        negated = False
        if self.peek() == 94:  # ^
            negated = True
            self.pos += 1
        ranges: List[Tuple[int, int]] = []
        while True:
            c = self.peek()
            if c is None:
                raise _unsupported("unbalanced [")
            if c == 93:  # ]
                self.pos += 1
                return ("class", ranges, negated)
            lo_ranges, lo = self.class_atom()
            if self.peek() == 45:  # -
                self.pos += 1
                if self.peek() == 93:
                    raise _unsupported("- must be escaped inside [...]")
                if lo is None:
                    raise _unsupported("a range in [...] must run between two characters")
                if self.peek() is None:
                    raise _unsupported("unbalanced [")
                _hi_ranges, hi = self.class_atom()
                if hi is None:
                    raise _unsupported("a range in [...] must run between two characters")
                if lo > hi:
                    raise _unsupported("a range in [...] runs backwards")
                ranges.append((lo, hi))
            elif lo is not None:
                ranges.append((lo, lo))
            else:
                ranges.extend(lo_ranges)

    def class_atom(self) -> tuple:
        c = self.cps[self.pos]
        ch = chr(c)
        if ch == "\\":
            self.pos += 1
            ranges, negated, single = self.parse_escape(True)
            return (_complement(ranges) if negated else ranges, single)
        if ch in CLASS_SYNTAX:
            raise _unsupported(ch + " must be escaped inside [...]")
        if ch in DOUBLED and self.pos + 1 < self.end and self.cps[self.pos + 1] == c:
            raise _unsupported(ch + ch + " is reserved inside [...]")
        self.pos += 1
        return ([(c, c)], c)

    def read_braces(self) -> Optional[Tuple[int, int]]:
        # {n}, {n,} or {n,m} at pos, or None (pos unchanged) when it is not one.
        p = self.pos + 1

        def number() -> Optional[int]:
            nonlocal p
            start = p
            n = 0
            while p < self.end and _is_ascii_digit(self.cps[p]):
                n = min(n * 10 + (self.cps[p] - 48), MAX_REPEAT + 1)
                p += 1
            return None if p == start else n

        lo = number()
        if lo is None:
            return None
        hi: Optional[int] = lo
        if p < self.end and self.cps[p] == 44:  # ,
            p += 1
            hi = number()
            if hi is None:
                hi = -1
        if p >= self.end or self.cps[p] != 125:  # }
            return None
        self.pos = p + 1
        return (lo, hi)

    def braces_ahead(self) -> bool:
        saved = self.pos
        found = self.read_braces() is not None
        self.pos = saved
        return found

    def parse_quantifier(self) -> Tuple[int, int]:
        c = self.peek()
        if c == 42:
            self.pos += 1
            q = (0, -1)
        elif c == 43:
            self.pos += 1
            q = (1, -1)
        elif c == 63:
            self.pos += 1
            q = (0, 1)
        elif c == 123:
            braces = self.read_braces()
            if braces is None:
                raise _unsupported("a lone { must be escaped as \\{")
            q = braces
            if q[0] > MAX_REPEAT or q[1] > MAX_REPEAT:
                raise _unsupported("a repeat count above %d" % MAX_REPEAT)
            if q[1] != -1 and q[0] > q[1]:
                raise _unsupported("a repeat {n,m} with n above m")
        else:
            return (1, 1)
        if self.peek() == 63:
            self.pos += 1  # lazy: the same answer for a whole-string match
        nxt = self.peek()
        if nxt in (42, 43, 63) or (nxt == 123 and self.braces_ahead()):
            raise _unsupported("nothing to repeat: a quantifier follows a quantifier")
        return q


# The program: ["char", ranges, negated], ["split", x, y], ["jmp", x], ["match"].
class _Compiler:
    def __init__(self) -> None:
        self.prog: list = []

    def push(self, op: list) -> int:
        if len(self.prog) >= MAX_PROGRAM:
            raise _unsupported("it expands to too large a program")
        self.prog.append(op)
        return len(self.prog) - 1

    def alt(self, alt: list) -> None:
        jumps = []
        for i, seq in enumerate(alt):
            if i < len(alt) - 1:
                split = self.push(["split", 0, 0])
                self.prog[split][1] = len(self.prog)
                self.seq(seq)
                jumps.append(self.push(["jmp", 0]))
                self.prog[split][2] = len(self.prog)
            else:
                self.seq(seq)
        for j in jumps:
            self.prog[j][1] = len(self.prog)

    def seq(self, seq: list) -> None:
        for atom, lo, hi in seq:
            for _ in range(lo):
                self.atom(atom)
            if hi == -1:
                split = self.push(["split", 0, 0])
                self.prog[split][1] = len(self.prog)
                self.atom(atom)
                self.push(["jmp", split])
                self.prog[split][2] = len(self.prog)
            else:
                splits = []
                for _ in range(lo, hi):
                    split = self.push(["split", 0, 0])
                    self.prog[split][1] = len(self.prog)
                    splits.append(split)
                    self.atom(atom)
                for s in splits:
                    self.prog[s][2] = len(self.prog)

    def atom(self, atom: tuple) -> None:
        if atom[0] == "class":
            self.push(["char", atom[1], atom[2]])
        else:
            self.alt(atom[1])


def _in_class(ranges: list, negated: bool, c: int) -> bool:
    hit = any(lo <= c <= hi for lo, hi in ranges)
    return hit != negated


def _add_thread(prog: list, out: list, seen: list, pc: int) -> None:
    stack = [pc]
    while stack:
        p = stack.pop()
        if seen[p]:
            continue
        seen[p] = True
        op = prog[p]
        if op[0] == "jmp":
            stack.append(op[1])
        elif op[0] == "split":
            stack.append(op[2])
            stack.append(op[1])
        else:
            out.append(p)


def matches_pattern(pattern: str, value: str) -> bool:
    """Whether the whole value matches the pattern, as an input's pattern
    attribute checks it (the browser wraps it as ^(?:pattern)$). Raises on
    anything outside the portable subset, so a pattern the server cannot check
    exactly as the browser does is caught when it is written."""
    cps = [ord(ch) for ch in pattern]
    if len(cps) > MAX_PATTERN:
        raise ValueError("pattern is too long: at most %d characters" % MAX_PATTERN)
    start = 0
    end = len(cps)
    if end > 0 and cps[0] == 94:
        start = 1
    # A trailing $ is the end anchor unless it is escaped (an odd run of backslashes before it).
    if end > start and cps[end - 1] == 36:
        slashes = 0
        i = end - 2
        while i >= start and cps[i] == 92:
            slashes += 1
            i -= 1
        if slashes % 2 == 0:
            end -= 1
    parser = _Parser(cps, end, start)
    alt = parser.parse_alt(0)
    if parser.pos != end:
        raise _unsupported("unbalanced )")

    compiler = _Compiler()
    compiler.alt(alt)
    compiler.push(["match"])
    prog = compiler.prog

    current: list = []
    _add_thread(prog, current, [False] * len(prog), 0)
    for ch in value:
        c = ord(ch)
        nxt: list = []
        seen = [False] * len(prog)
        for pc in current:
            op = prog[pc]
            if op[0] == "char" and _in_class(op[1], op[2], c):
                _add_thread(prog, nxt, seen, pc + 1)
        current = nxt
        if not current:
            return False
    return any(prog[pc][0] == "match" for pc in current)

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add text.pattern-match
Download for Python text.pattern-match-1.0.0-python.fune · 28,532 bytes sha256 319d4839a04496c2070f36d1bb098f6c707e6ee1cdeee15b9f642670575b1a0a

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./text.pattern-match-1.0.0-python.fune, or fetch it from a terminal with fune pull text.pattern-match@1.0.0:python.

The whole function, every language, is one file too: text.pattern-match-1.0.0.fune, 59,895 bytes, sha256 1601403c75ad3e25b15c2e3f7d9139527e1011000f684c2bd84bfcbb196c864f. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before text.pattern-match

after — your function gets the result and the arguments, and returns the final result.

# fune: after text.pattern-match

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show text.pattern-match --steps.

# fune: step text.pattern-match after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
five digits: a US ZIP code matches [0-9]{5}, 90210 → true
the whole value must match: four digits of five do not [0-9]{5}, 9021 → false
the whole value must match: a sixth digit is not ignored [0-9]{5}, 902101 → false
a trailing newline is not part of a match (Python's $ would allow it) [0-9]{5}, 90210 → false
\d is ASCII: an Arabic-Indic digit is not a digit \d{3}, ١٢٣ → false
\d+ matches ASCII digits \d+, 0123456789 → true
a UK mobile number with optional spaces 07\d{3} ?\d{3} ?\d{3}, 07700 900 982 → true
alternation inside a non-capturing group (?:GB|IE)[0-9]{2}, IE42 → true
alternation at the top level covers the whole value either way cat|dog, catdog → false
^ and $ at the ends are allowed and change nothing ^[A-Z]{3}$, GBP → true
Show the other 37 tests
CaseArgumentsExpected
an escaped $ at the end is a literal dollar [0-9]+\$, 100$ → true
an optional letter: colour or color colou?r, color → true
a bounded repeat {2,3} refuses four x{2,3}, xxxx → false
{2,} has no upper bound x{2,}, xxxxxxxx → true
a negated class with a range [^a-z]+, ABC-123 → true
a negated class refuses what it lists [^a-z]+, ABc → false
\w is ASCII letters, digits and underscore only \w+, café → false
\s is ASCII whitespace a\sb, a b → true
. matches one code point, an emoji included a.b, a😀b → true
. does not match a newline a.b, a b → false
a non-ASCII literal matches itself café, café → true
an escaped dot is a literal dot v\d+\.\d+, v1x2 → false
an escaped - inside a class is a literal hyphen [A-Z\-]+, AB-CD → true
nested repeats that blow up a backtracking engine answer at once (a+)+b, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac → false
a lazy quantifier gives the same whole-string answer a+?b, aaab → true
the empty pattern matches only the empty value , → true
the empty pattern refuses anything else , a → false
a star matches the empty value [0-9]*, → true
case matters: there is no ignore-case flag [a-z]+, Abc → false
lookahead is refused (?=.*\d).{8,}, password1 → error: unsupported pattern
a backreference is refused (a)\1, aa → error: unsupported pattern
\b is refused \bword\b, word → error: unsupported pattern
a Unicode property escape is refused \p{L}+, abc → error: unsupported pattern
a named group is refused (?<year>\d{4}), 2026 → error: unsupported pattern
an unclosed group is refused (ab, ab → error: unsupported pattern
an unopened group is refused ab), ab → error: unsupported pattern
an unclosed class is refused [a-z, a → error: unsupported pattern
a backwards range is refused [z-a], a → error: unsupported pattern
a quantifier with nothing to repeat is refused *a, a → error: unsupported pattern
two quantifiers in a row are refused a**, a → error: unsupported pattern
{n,m} with n above m is refused a{3,2}, aa → error: unsupported pattern
a repeat count above 1000 is refused a{1001}, a → error: unsupported pattern
an unescaped hyphen at the end of a class is refused, as the browser's v flag does [a-z-], a → error: unsupported pattern
^ in the middle of the pattern is refused a^b, ab → error: unsupported pattern
a pattern of exactly 1000 characters is accepted aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa… → true
repeats that expand past the program limit are refused (?:(?:a{1000}){1000}), a → error: unsupported pattern
a pattern of 1001 characters is refused aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa… → error: pattern is too long

Verification

Verified by the operator, not the sandbox 47 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

## Why not the language's own regex

The three engines disagree. Python's `$` matches before a trailing newline, its `\d` and `\w` are Unicode (`"٣"` is a digit), and `re` has no `v` flag; Rust's standard library has no regex at all (and a crate is not allowed); JavaScript's `\s` takes Unicode spaces. A pattern checked by three engines is three rules. This is one small engine written three times, pinned by the same vectors, and checked against the browser's own `RegExp(…, "v")` by a differential fuzz while it was written (no disagreement on any pattern both accept).

## The supported subset

| Syntax | Meaning | |--------|---------| | `a`, `é`, `😀` | that code point | | `.` | any code point but a line terminator (`\n`, `\r`, U+2028, U+2029) | | `\d` `\D` | ASCII digit `[0-9]`, and not | | `\w` `\W` | ASCII word character `[A-Za-z0-9_]`, and not | | `\s` `\S` | ASCII whitespace (space, `\t`, `\n`, `\v`, `\f`, `\r`), and not | | `\t` `\n` `\v` `\f` `\r` | those control characters | | `\.` `\*` `\(` … | an escaped syntax character `^ $ \ . * + ? ( ) [ ] { } \| /` | | `[abc]` `[a-z]` `[^0-9]` | a class, with ranges, negation and the escapes above; inside a class `\-` `\&` `\!` `\#` `\%` `\,` `\:` `\;` `\<` `\=` `\>` `\@` `` \` `` `\~` are literals too | | `(…)` `(?:…)` | a group (nothing is captured: whole-string matching has no use for it) | | `a\|b` | alternation | | `*` `+` `?` `{n}` `{n,}` `{n,m}` | repeats, with a lazy `?` suffix accepted (it cannot change a whole-string answer) | | `^` first, `$` last | allowed and ignored: the match is always of the whole value |

Everything is over Unicode code points, as the `v` flag is. There is no ignore-case: list both cases (`[A-Za-z]`).

## What is refused, and why

`matchesPattern` throws `unsupported pattern: <what>` (the same phrase in every language) for:

- lookahead and lookbehind (`(?=` `(?!` `(?<=` `(?<!`), named groups, inline flags: they cannot be run in linear time, or are rarely used in a pattern attribute; - backreferences (`\1`, `\k<…>`), `\b` and `\B`, `\p{…}`, `\u…`, `\x…`, `\c…`, `\0`, and any other escaped letter or punctuation the `v` flag rejects; - `^` or `$` anywhere but the very start and end of the pattern; - an unbalanced `(`, `)`, `[`, a lone `]`, `{` or `}`; - the `v` flag's own class rules: an unescaped `( ) [ ] { } / - \ |` inside `[…]` (so `[A-Za-z-]` must be written `[A-Za-z\-]`; the browser ignores the former pattern entirely), and doubled punctuators such as `&&`; - a range written backwards (`[z-a]`) or with a class at either end (`[\d-z]`); - a quantifier with nothing before it, or straight after another (`a**`); - `{n,m}` with n above m, or a count above 1000; - a pattern that would compile to more than 20,000 steps (nested counted repeats such as `(a{1000}){1000}`).

A pattern over 1000 code points throws `pattern is too long`.

A refused pattern is a programming error, not a user's typing error: it is thrown whatever the value, so it fails the first test that uses it.

## Linear time

The pattern compiles to a program run as a Thompson NFA (a Pike VM without captures): each character of the value is looked at once against each program step, so `(a+)+b` against 10,000 `a`s answers at once. A backtracking engine takes exponential time on it, which is how a pattern on a public form becomes a denial of service on the server that re-checks it.

## Differences from the browser

Only where the browser's own rules are wider than the subset: `\s` here is ASCII whitespace, where JavaScript's also takes no-break and other Unicode spaces. Every pattern the subset accepts is one the browser accepts, and on the values tested they agree.

Files

PathBytes
README.md4,337
impl/python.py13,048
impl/rust.rs16,398
impl/typescript.ts13,779
vectors.json8,160