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 matchesmatches_pattern([0-9]{5}, 9021)→ false the whole value must match: four digits of five do notmatches_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.
pub fn matches_pattern(pattern: &str, value: &str) -> bool
| pattern | string | a regular expression in the portable subset the README lists, as an input's pattern attribute takes it |
| value | string | the text to test; the pattern must match all of it, as the browser's pattern check does |
| returns | bool | true when the whole value matches |
Your code names it in one line, in the file that uses it
fune!(text.pattern-match@^1); // then call matches_pattern(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
// 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. Everything is over Unicode code points (chars), as the browser's
// v-flag regex is.
const MAX_PATTERN: usize = 1000;
const MAX_REPEAT: i64 = 1000;
const MAX_PROGRAM: usize = 20000;
const MAX_CODE_POINT: u32 = 0x10FFFF;
type Range = (u32, u32);
const DIGIT: &[Range] = &[(48, 57)];
const WORD: &[Range] = &[(48, 57), (65, 90), (95, 95), (97, 122)];
const SPACE: &[Range] = &[(9, 13), (32, 32)];
// What `.` does not match: the line terminators, as in JavaScript.
const LINE_ENDS: &[Range] = &[(10, 10), (13, 13), (0x2028, 0x2029)];
const SYNTAX: &str = "^$\\.*+?()[]{}|/";
const CLASS_SYNTAX: &str = "()[]{}/-\\|";
const DOUBLED: &str = "&!#$%*+,.:;<=>?@^`~";
const CLASS_PUNCTUATORS: &str = "&-!#%,:;<=>@`~";
enum Atom {
Class(Vec<Range>, bool),
Group(Vec<Vec<Node>>),
}
struct Node {
atom: Atom,
min: i64,
max: i64, // -1: unbounded
}
fn unsupported(detail: &str) -> ! {
panic!("unsupported pattern: {}", detail)
}
fn is_ascii_digit(c: u32) -> bool {
(48..=57).contains(&c)
}
fn complement(ranges: &[Range]) -> Vec<Range> {
let mut sorted: Vec<Range> = ranges.to_vec();
sorted.sort_by_key(|r| r.0);
let mut out = Vec::new();
let mut next: u32 = 0;
for (lo, hi) in sorted {
if lo > next {
out.push((next, lo - 1));
}
if hi + 1 > next {
next = hi + 1;
}
}
if next <= MAX_CODE_POINT {
out.push((next, MAX_CODE_POINT));
}
out
}
struct Parser {
cps: Vec<u32>,
end: usize,
pos: usize,
}
struct Escape {
ranges: Vec<Range>,
negated: bool,
single: Option<u32>,
}
fn ch_of(c: u32) -> char {
char::from_u32(c).unwrap_or('\u{FFFD}')
}
impl Parser {
fn peek(&self) -> Option<u32> {
if self.pos < self.end {
Some(self.cps[self.pos])
} else {
None
}
}
fn parse_alt(&mut self, depth: usize) -> Vec<Vec<Node>> {
let mut alt = vec![self.parse_seq(depth)];
while self.peek() == Some(124) {
self.pos += 1;
alt.push(self.parse_seq(depth));
}
alt
}
fn parse_seq(&mut self, depth: usize) -> Vec<Node> {
let mut seq = Vec::new();
loop {
match self.peek() {
None | Some(124) => return seq,
Some(41) => {
if depth == 0 {
unsupported("unbalanced )");
}
return seq;
}
_ => {}
}
let atom = self.parse_atom(depth);
let (min, max) = self.parse_quantifier();
seq.push(Node { atom, min, max });
}
}
fn parse_atom(&mut self, depth: usize) -> Atom {
let c = self.cps[self.pos];
let ch = ch_of(c);
match ch {
'*' | '+' | '?' => unsupported(&format!("nothing to repeat before {}", ch)),
'{' => {
if self.read_braces().is_some() {
unsupported("nothing to repeat before {");
}
unsupported("a lone { must be escaped as \\{")
}
'}' | ']' => unsupported(&format!("a lone {} must be escaped as \\{}", ch, ch)),
'^' => unsupported("^ is only supported at the start of the pattern"),
'$' => unsupported("$ is only supported at the end of the pattern"),
'.' => {
self.pos += 1;
Atom::Class(LINE_ENDS.to_vec(), true)
}
'(' => {
self.pos += 1;
if self.peek() == Some(63) {
if self.pos + 1 < self.end && self.cps[self.pos + 1] == 58 {
self.pos += 2;
} else {
unsupported("lookaround, named groups and flags are not supported");
}
}
let alt = self.parse_alt(depth + 1);
if self.peek() != Some(41) {
unsupported("unbalanced (");
}
self.pos += 1;
Atom::Group(alt)
}
'[' => self.parse_class(),
'\\' => {
self.pos += 1;
let e = self.parse_escape(false);
Atom::Class(e.ranges, e.negated)
}
_ => {
self.pos += 1;
Atom::Class(vec![(c, c)], false)
}
}
}
// After a backslash: a class escape, a control escape or escaped punctuation.
fn parse_escape(&mut self, in_class: bool) -> Escape {
let c = match self.peek() {
Some(c) => c,
None => unsupported("the pattern ends with a lone \\"),
};
self.pos += 1;
let ch = ch_of(c);
let class = |ranges: &[Range], negated: bool| Escape { ranges: ranges.to_vec(), negated, single: None };
let single = |n: u32| Escape { ranges: vec![(n, n)], negated: false, single: Some(n) };
match ch {
'd' => return class(DIGIT, false),
'D' => return class(DIGIT, true),
'w' => return class(WORD, false),
'W' => return class(WORD, true),
's' => return class(SPACE, false),
'S' => return class(SPACE, true),
't' => return single(9),
'n' => return single(10),
'v' => return single(11),
'f' => return single(12),
'r' => return single(13),
_ => {}
}
// Escaped punctuation: what the v flag accepts, the syntax characters
// everywhere and the reserved punctuators inside [...].
if SYNTAX.contains(ch) || (in_class && CLASS_PUNCTUATORS.contains(ch)) {
return single(c);
}
unsupported(&format!("\\{} is not supported (backreferences, \\b, \\p, \\u and \\x are not)", ch))
}
fn parse_class(&mut self) -> Atom {
self.pos += 1; // [
let mut negated = false;
if self.peek() == Some(94) {
negated = true;
self.pos += 1;
}
let mut ranges: Vec<Range> = Vec::new();
loop {
match self.peek() {
None => unsupported("unbalanced ["),
Some(93) => {
self.pos += 1;
return Atom::Class(ranges, negated);
}
_ => {}
}
let (lo_ranges, lo) = self.class_atom();
if self.peek() == Some(45) {
self.pos += 1;
if self.peek() == Some(93) {
unsupported("- must be escaped inside [...]");
}
let lo = match lo {
Some(lo) => lo,
None => unsupported("a range in [...] must run between two characters"),
};
if self.peek().is_none() {
unsupported("unbalanced [");
}
let (_, hi) = self.class_atom();
let hi = match hi {
Some(hi) => hi,
None => unsupported("a range in [...] must run between two characters"),
};
if lo > hi {
unsupported("a range in [...] runs backwards");
}
ranges.push((lo, hi));
} else if let Some(lo) = lo {
ranges.push((lo, lo));
} else {
ranges.extend(lo_ranges);
}
}
}
fn class_atom(&mut self) -> (Vec<Range>, Option<u32>) {
let c = self.cps[self.pos];
let ch = ch_of(c);
if ch == '\\' {
self.pos += 1;
let e = self.parse_escape(true);
let ranges = if e.negated { complement(&e.ranges) } else { e.ranges };
return (ranges, e.single);
}
if CLASS_SYNTAX.contains(ch) {
unsupported(&format!("{} must be escaped inside [...]", ch));
}
if DOUBLED.contains(ch) && self.pos + 1 < self.end && self.cps[self.pos + 1] == c {
unsupported(&format!("{}{} is reserved inside [...]", ch, ch));
}
self.pos += 1;
(vec![(c, c)], Some(c))
}
// {n}, {n,} or {n,m} at pos, or None (pos unchanged) when it is not one.
fn read_braces(&mut self) -> Option<(i64, i64)> {
let mut p = self.pos + 1;
let number = |p: &mut usize| -> Option<i64> {
let start = *p;
let mut n: i64 = 0;
while *p < self.end && is_ascii_digit(self.cps[*p]) {
n = (n * 10 + (self.cps[*p] as i64 - 48)).min(MAX_REPEAT + 1);
*p += 1;
}
if *p == start {
None
} else {
Some(n)
}
};
let min = number(&mut p)?;
let mut max = min;
if p < self.end && self.cps[p] == 44 {
p += 1;
max = number(&mut p).unwrap_or(-1);
}
if p >= self.end || self.cps[p] != 125 {
return None;
}
self.pos = p + 1;
Some((min, max))
}
fn braces_ahead(&mut self) -> bool {
let saved = self.pos;
let found = self.read_braces().is_some();
self.pos = saved;
found
}
fn parse_quantifier(&mut self) -> (i64, i64) {
let q = match self.peek() {
Some(42) => {
self.pos += 1;
(0, -1)
}
Some(43) => {
self.pos += 1;
(1, -1)
}
Some(63) => {
self.pos += 1;
(0, 1)
}
Some(123) => {
let q = match self.read_braces() {
Some(q) => q,
None => unsupported("a lone { must be escaped as \\{"),
};
if q.0 > MAX_REPEAT || q.1 > MAX_REPEAT {
unsupported(&format!("a repeat count above {}", MAX_REPEAT));
}
if q.1 != -1 && q.0 > q.1 {
unsupported("a repeat {n,m} with n above m");
}
q
}
_ => return (1, 1),
};
if self.peek() == Some(63) {
self.pos += 1; // lazy: the same answer for a whole-string match
}
let next = self.peek();
if matches!(next, Some(42) | Some(43) | Some(63)) || (next == Some(123) && self.braces_ahead()) {
unsupported("nothing to repeat: a quantifier follows a quantifier");
}
q
}
}
// The program: a character test, a fork, a jump or the match.
enum Op {
Char(Vec<Range>, bool),
Split(usize, usize),
Jmp(usize),
Match,
}
struct Compiler {
prog: Vec<Op>,
}
impl Compiler {
fn push(&mut self, op: Op) -> usize {
if self.prog.len() >= MAX_PROGRAM {
unsupported("it expands to too large a program");
}
self.prog.push(op);
self.prog.len() - 1
}
fn set_x(&mut self, at: usize, to: usize) {
match &mut self.prog[at] {
Op::Split(x, _) | Op::Jmp(x) => *x = to,
_ => {}
}
}
fn set_y(&mut self, at: usize, to: usize) {
if let Op::Split(_, y) = &mut self.prog[at] {
*y = to;
}
}
fn alt(&mut self, alt: &[Vec<Node>]) {
let mut jumps = Vec::new();
for (i, seq) in alt.iter().enumerate() {
if i < alt.len() - 1 {
let split = self.push(Op::Split(0, 0));
let here = self.prog.len();
self.set_x(split, here);
self.seq(seq);
jumps.push(self.push(Op::Jmp(0)));
let here = self.prog.len();
self.set_y(split, here);
} else {
self.seq(seq);
}
}
let here = self.prog.len();
for j in jumps {
self.set_x(j, here);
}
}
fn seq(&mut self, seq: &[Node]) {
for node in seq {
for _ in 0..node.min {
self.atom(&node.atom);
}
if node.max == -1 {
let split = self.push(Op::Split(0, 0));
let here = self.prog.len();
self.set_x(split, here);
self.atom(&node.atom);
self.push(Op::Jmp(split));
let here = self.prog.len();
self.set_y(split, here);
} else {
let mut splits = Vec::new();
for _ in node.min..node.max {
let split = self.push(Op::Split(0, 0));
let here = self.prog.len();
self.set_x(split, here);
splits.push(split);
self.atom(&node.atom);
}
let here = self.prog.len();
for s in splits {
self.set_y(s, here);
}
}
}
}
fn atom(&mut self, atom: &Atom) {
match atom {
Atom::Class(ranges, negated) => {
self.push(Op::Char(ranges.clone(), *negated));
}
Atom::Group(alt) => self.alt(alt),
}
}
}
fn add_thread(prog: &[Op], out: &mut Vec<usize>, seen: &mut [bool], pc: usize) {
let mut stack = vec![pc];
while let Some(p) = stack.pop() {
if seen[p] {
continue;
}
seen[p] = true;
match &prog[p] {
Op::Jmp(x) => stack.push(*x),
Op::Split(x, y) => {
stack.push(*y);
stack.push(*x);
}
_ => out.push(p),
}
}
}
/// Whether the whole value matches the pattern, as an input's pattern
/// attribute checks it (the browser wraps it as ^(?:pattern)$).
///
/// # Panics
/// Panics with "unsupported pattern: ..." on anything outside the portable
/// subset, and "pattern is too long" over 1000 characters, so a pattern the
/// server cannot check exactly as the browser does is caught when written.
pub fn matches_pattern(pattern: &str, value: &str) -> bool {
let cps: Vec<u32> = pattern.chars().map(|c| c as u32).collect();
if cps.len() > MAX_PATTERN {
panic!("pattern is too long: at most {} characters", MAX_PATTERN);
}
let mut start = 0;
let mut end = cps.len();
if end > 0 && 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 && cps[end - 1] == 36 {
let mut slashes = 0;
let mut i = end - 1;
while i > start && cps[i - 1] == 92 {
slashes += 1;
i -= 1;
}
if slashes % 2 == 0 {
end -= 1;
}
}
let mut parser = Parser { cps, end, pos: start };
let alt = parser.parse_alt(0);
if parser.pos != end {
unsupported("unbalanced )");
}
let mut compiler = Compiler { prog: Vec::new() };
compiler.alt(&alt);
compiler.push(Op::Match);
let prog = compiler.prog;
let mut current = Vec::new();
add_thread(&prog, &mut current, &mut vec![false; prog.len()], 0);
for ch in value.chars() {
let c = ch as u32;
let mut next = Vec::new();
let mut seen = vec![false; prog.len()];
for &pc in ¤t {
if let Op::Char(ranges, negated) = &prog[pc] {
let hit = ranges.iter().any(|&(lo, hi)| c >= lo && c <= hi);
if hit != *negated {
add_thread(&prog, &mut next, &mut seen, pc + 1);
}
}
}
current = next;
if current.is_empty() {
return false;
}
}
current.iter().any(|&pc| matches!(prog[pc], Op::Match))
}
pub fn fune_vector(args: &[Value]) -> Value {
Value::Bool(matches_pattern(args[0].as_str(), args[1].as_str()))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add text.pattern-match
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./text.pattern-match-1.0.0-rust.fune, or fetch it from a terminal with fune pull text.pattern-match@1.0.0:rust.
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.
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Path | Bytes |
|---|---|
| README.md | 4,337 |
| impl/python.py | 13,048 |
| impl/rust.rs | 16,398 |
| impl/typescript.ts | 13,779 |
| vectors.json | 8,160 |