packages

regex

On this page

Regular expressions with a linear-time guarantee, in the style of RE2 and Rust's regex.

A pattern compiles to a Thompson NFA over UTF-8 bytes. is_match and find run a lazy DFA, forward for the end of a match and backward for its start, skipping ahead with literal prefilters; groups come from a one-pass DFA or a PikeVM. None of them backtracks, so a search takes time linear in the haystack for every pattern, (a*)*b included. In exchange there are no backreferences and no look-around, which cannot be matched that way.

nabi
use regex::Regex;

let re = try Regex::new(r"(?<user>[\w.]+)@(?<host>[\w.]+)");
let c = re.captures("write to [email protected] today")?;
assert(c["user"] == "ada" && c["host"] == "example.org");
assert(re.replace_all("[email protected], [email protected]", "${user} at ${host}") == "ada at a.org, bob at b.org");

Syntax: literals and escapes (\n, \x7F, \x{1F600}, é), ., classes [a-z] [^...] with nesting and && -- ~~, POSIX [[:alpha:]], Perl classes \d \w \s (Unicode) and \D \W \S, Unicode classes \pL \p{Greek} \p{sc=Latin} \P{..}, anchors ^ $ \A \z \b \B \< \> \b{start} \b{end}, repetition * + ? {n} {n,} {n,m} with lazy ? forms, alternation, groups (..), (?:..), (?<name>..), (?P<name>..), and flags i m s x U u, inline (?i) or scoped (?i:..). Unicode tables are UCD 18.0.0.

regex!("..") checks a literal pattern while the program compiles (a mistake is a compile error with the same message Regex::new would give) and compiles it once per thread at its first use:

nabi
use regex::regex!;

for line in ["id=7", "id=x"] {
    if regex!(r"^id=\d+$").is_match(line) { println(line); }
}

Structs

CapturesSource

pub struct Captures

The groups of one match. Group 0 is the whole match; a group that took no part in the match is none.

Index with a number or a name for the text: caps[1], caps["year"]. That panics when the group did not take part; get and name return none instead.

nabi
let re = try regex::Regex::new(r"(?<key>\w+)=(?<val>\w+)?");
let c = re.captures("x=")?;
assert(c["key"] == "x" && c.name("val") == none && c.len() == 3);
  • pub fn get(self, i: usize) -> Match | none§

    Source

    Group i, or none when it did not take part or does not exist.

    nabi
    let c = (try regex::Regex::new("(a)|(b)")).captures("b")?;
    assert(c.get(1) == none && c.get(2)?.as_str() == "b" && c.get(7) == none);
    
  • pub fn name(self, name: str) -> Match | none§

    Source

    The group named name, or none.

    nabi
    let c = (try regex::Regex::new(r"(?<n>\d+)")).captures("a42")?;
    assert(c.name("n")?.as_str() == "42" && c.name("m") == none);
    
  • pub fn len(self) -> usize§

    Source

    The number of groups, group 0 included (also those that did not take part).

    nabi
    assert((try regex::Regex::new("(a)(b)?")).captures("a")?.len() == 3);
    
  • pub fn iter(self) -> ListIntoIter<Match | none>§

    Source

    Every group in order.

    nabi
    let c = (try regex::Regex::new("(a)(x)?")).captures("a")?;
    let texts: List<str> = c.iter().map(|m| if let x: regex::Match = m { x.as_str() } else { "-" }).collect();
    assert(texts == ["a", "a", "-"]);
    
  • pub fn expand(self, template: str) -> str§

    Source

    template with $1, $name, ${1}, ${name} replaced by the group's text (empty when the group did not take part or does not exist) and $$ by $. A name runs as far as letters, digits and _ go, so write ${1}a for group 1 followed by a.

    nabi
    let c = (try regex::Regex::new(r"(?<first>\w+) (\w+)")).captures("Ada Lovelace")?;
    assert(c.expand("$2, ${first} ($$)") == "Lovelace, Ada ($)");
    
Trait implementations 3
  • impl Index<usize> for Captures
  • impl Index<str> for Captures
  • impl Debug for Captures

MatchSource

pub struct Match

One match: a span of the haystack, in byte offsets on char boundaries.

nabi
let re = try regex::Regex::new("b+");
let m = re.find("abbc")?;
assert(m.range() == (1..3) && m.len() == 2 && !m.is_empty());
  • pub fn start(self) -> usize§

    Source

    The byte offset where the match starts.

    nabi
    assert((try regex::Regex::new("c")).find("abc")?.start() == 2);
    
  • pub fn end(self) -> usize§

    Source

    The byte offset just past the match.

    nabi
    assert((try regex::Regex::new("c")).find("abc")?.end() == 3);
    
  • pub fn range(self) -> Range<usize>§

    Source

    start()..end().

    nabi
    assert((try regex::Regex::new("é")).find("café")?.range() == (3..5));
    
  • pub fn len(self) -> usize§

    Source

    The length in bytes.

    nabi
    assert((try regex::Regex::new("é+")).find("éé")?.len() == 4);
    
  • pub fn is_empty(self) -> bool§

    Source

    Whether the match is empty.

    nabi
    assert((try regex::Regex::new("x*")).find("abc")?.is_empty() ?? false);
    
  • pub fn as_str(self) -> str§

    Source

    The matched text.

    nabi
    assert((try regex::Regex::new(r"\d+")).find("ab12c")?.as_str() == "12");
    
Trait implementations 1
  • impl Display for Match

CaptureMatchesSource

pub struct CaptureMatches

The groups of each match of Regex::captures_iter.

Trait implementations 1
  • impl Iterator for CaptureMatches

MatchesSource

pub struct Matches

The matches of Regex::find_iter.

Trait implementations 1
  • impl Iterator for Matches

RegexSource

pub struct Regex

A compiled regular expression.

Matching is linear in the haystack: no pattern makes a search backtrack. Offsets are byte offsets into the haystack and always fall on char boundaries.

A Regex keeps its search caches inside, so it is not Sync: build one per thread.

nabi
use regex::Regex;

let re = try Regex::new(r"(\d{4})-(\d{2})-(\d{2})");
let m = re.find("on 2026-11-14.")?;
assert(m.start() == 3 && m.as_str() == "2026-11-14");
  • pub fn new(pattern: str) throws (RegexError) -> Regex§

    Source

    Compiles pattern with the default options.

    nabi
    let re = try regex::Regex::new(r"\bcat\b");
    assert(re.is_match("a cat sat") && !re.is_match("concat"));
    
  • pub fn as_str(self) -> str§

    Source

    The pattern as written.

    nabi
    assert((try regex::Regex::new("a|b")).as_str() == "a|b");
    
  • pub fn is_match(self, h: str) -> bool§

    Source

    Whether the regex matches anywhere in h.

    nabi
    let re = try regex::Regex::new(r"\d+");
    assert(re.is_match("abc123") && !re.is_match("abc"));
    
  • pub fn is_match_at(self, h: str, start: usize) -> bool§

    Source

    is_match for a search starting at byte start (a char boundary); the text before start still counts for ^ and \b.

    nabi
    let re = try regex::Regex::new(r"\bb");
    assert(!re.is_match_at("ab", 1));
    
  • pub fn shortest_match(self, h: str) -> usize | none§

    Source

    The end of the first match the engine sees, which may be shorter than the one find reports; the cheapest search after is_match.

    nabi
    let re = try regex::Regex::new("a+");
    assert(re.shortest_match("baaa")? == 2);
    
  • pub fn shortest_match_at(self, h: str, start: usize) -> usize | none§

    Source

    shortest_match from byte start.

    nabi
    let re = try regex::Regex::new("a+");
    assert(re.shortest_match_at("aba", 1)? == 3);
    
  • pub fn find(self, h: str) -> Match | none§

    Source

    The leftmost-first match in h.

    nabi
    let re = try regex::Regex::new("[a-z]+");
    let m = re.find("12 abc 34")?;
    assert(m.start() == 3 && m.end() == 6 && m.as_str() == "abc");
    
  • pub fn find_at(self, h: str, start: usize) -> Match | none§

    Source

    find from byte start (a char boundary); the text before start still counts for ^ and \b.

    nabi
    let re = try regex::Regex::new("a");
    assert(re.find_at("aXa", 1)?.start() == 2);
    
  • pub fn find_iter(self, h: str) -> Matches§

    Source

    Every non-overlapping match, left to right. An empty match right after the previous match is skipped, so a* on "baaab" yields "", "aaa", "" (at 0, 1..4 and 5).

    nabi
    let re = try regex::Regex::new(r"\d+");
    let all: List<str> = re.find_iter("1, 22 and 333").map(|m| m.as_str()).collect();
    assert(all == ["1", "22", "333"]);
    
  • pub fn captures(self, h: str) -> Captures | none§

    Source

    The groups of the leftmost-first match.

    nabi
    let re = try regex::Regex::new(r"(?<y>\d{4})-(\d{2})");
    let c = re.captures("in 2026-11")?;
    assert(c[0] == "2026-11" && c["y"] == "2026" && c[2] == "11");
    
  • pub fn captures_at(self, h: str, start: usize) -> Captures | none§

    Source

    captures from byte start.

    nabi
    let re = try regex::Regex::new(r"(\d)");
    assert(re.captures_at("1 2", 1)?[1] == "2");
    
  • pub fn captures_iter(self, h: str) -> CaptureMatches§

    Source

    The groups of every match, left to right (the matches of find_iter).

    nabi
    let re = try regex::Regex::new(r"(\w)=(\d)");
    let keys: List<str> = re.captures_iter("a=1 b=2").map(|c| c[1]).collect();
    assert(keys == ["a", "b"]);
    
  • pub fn split(self, h: str) -> Split§

    Source

    The pieces of h between matches. A match at either end gives an empty piece there.

    nabi
    let re = try regex::Regex::new(r"[,;]\s*");
    let parts: List<str> = re.split("a, b;c").collect();
    assert(parts == ["a", "b", "c"]);
    
  • pub fn splitn(self, h: str, limit: usize) -> SplitN§

    Source

    At most limit pieces of split; the last holds the rest of h unsplit.

    nabi
    let re = try regex::Regex::new(",");
    let parts: List<str> = re.splitn("a,b,c", 2).collect();
    assert(parts == ["a", "b,c"]);
    
  • pub fn captures_len(self) -> usize§

    Source

    The number of groups, group 0 (the whole match) included.

    nabi
    assert((try regex::Regex::new("(a)(?:b)(c)")).captures_len() == 3);
    
  • pub fn capture_names(self) -> List<str | none>§

    Source

    Each group's name, none for unnamed ones; group 0 first.

    nabi
    let re = try regex::Regex::new("(?<a>x)(y)");
    assert(re.capture_names() == [none, "a", none]);
    
  • pub fn replace<R: Replacer>(self, h: str, rep: R) -> str§

    Source

    h with the first match replaced by rep.

    nabi
    let re = try regex::Regex::new(r"(\w+)@(\w+)");
    assert(re.replace("mail ann@home now", "$2 at $1") == "mail home at ann now");
    
  • pub fn replace_all<R: Replacer>(self, h: str, rep: R) -> str§

    Source

    h with every match replaced by rep.

    nabi
    let re = try regex::Regex::new(r"\s+");
    assert(re.replace_all("a  b \t c", " ") == "a b c");
    
  • pub fn replacen<R: Replacer>(self, h: str, limit: usize, rep: R) -> str§

    Source

    h with the first limit matches replaced by rep; limit 0 replaces all of them.

    nabi
    let re = try regex::Regex::new("a");
    assert(re.replacen("aaaa", 2, "b") == "bbaa");
    
Trait implementations 2
  • impl Display for Regex
  • impl Debug for Regex

RegexBuilderSource

pub struct RegexBuilder

Options for building a Regex. Each flag here sets the default that inline flags such as (?i) can still change.

nabi
use regex::RegexBuilder;

let re = try RegexBuilder::new("^hello$").case_insensitive(true).multi_line(true).build();
assert(re.is_match("say\nHELLO\n"));
  • pub fn new(pattern: str) -> RegexBuilder§

    Source

    A builder for pattern with the default options.

    nabi
    let re = try regex::RegexBuilder::new("a+").build();
    assert(re.is_match("caaat"));
    
  • pub fn case_insensitive(self, yes: bool) -> RegexBuilder§

    Source

    Letters match their other cases (Unicode simple case folding), as with (?i).

    nabi
    let re = try regex::RegexBuilder::new("straße").case_insensitive(true).build();
    assert(re.is_match("STRAßE"));
    
  • pub fn multi_line(self, yes: bool) -> RegexBuilder§

    Source

    ^ and $ match at line starts and ends too, as with (?m).

    nabi
    let re = try regex::RegexBuilder::new("^b").multi_line(true).build();
    assert(re.is_match("a\nb"));
    
  • pub fn dot_matches_new_line(self, yes: bool) -> RegexBuilder§

    Source

    . matches \n too, as with (?s).

    nabi
    let re = try regex::RegexBuilder::new("a.b").dot_matches_new_line(true).build();
    assert(re.is_match("a\nb"));
    
  • pub fn swap_greed(self, yes: bool) -> RegexBuilder§

    Source

    Greedy and lazy repetition trade places, as with (?U).

    nabi
    let re = try regex::RegexBuilder::new("a+").swap_greed(true).build();
    assert(re.find("aaa")?.as_str() == "a");
    
  • pub fn ignore_whitespace(self, yes: bool) -> RegexBuilder§

    Source

    Whitespace in the pattern is ignored and # starts a comment, as with (?x).

    nabi
    let re = try regex::RegexBuilder::new("a b # comment").ignore_whitespace(true).build();
    assert(re.is_match("ab"));
    
  • pub fn unicode(self, yes: bool) -> RegexBuilder§

    Source

    Unicode-aware \w, \d, \s, \b and case folding (on by default); off, they are ASCII only, as with (?-u).

    nabi
    let re = try regex::RegexBuilder::new(r"^\w$").unicode(false).build();
    assert(re.is_match("a") && !re.is_match("é"));
    
  • pub fn size_limit(self, bytes: usize) -> RegexBuilder§

    Source

    The most bytes the compiled program may take (10 MiB by default); a larger pattern fails with RegexError::TooBig.

    nabi
    let r = try { _ = try regex::RegexBuilder::new(r"\w{100}").size_limit(1000).build(); true } catch _: regex::RegexError { false };
    assert(!r);
    
  • pub fn dfa_size_limit(self, bytes: usize) -> RegexBuilder§

    Source

    The most bytes each lazy DFA cache may take (2 MiB by default). A search that keeps overflowing it falls back to the slower PikeVM; it never fails.

    nabi
    let re = try regex::RegexBuilder::new("[a-z]+").dfa_size_limit(4096).build();
    assert(re.is_match("abc"));
    
  • pub fn build(self) throws (RegexError) -> Regex§

    Source

    Compiles the pattern.

    nabi
    let ok = try { _ = try regex::RegexBuilder::new("(").build(); true } catch _: regex::RegexError { false };
    assert(!ok);
    

SplitSource

pub struct Split

The pieces of Regex::split.

Trait implementations 1
  • impl Iterator for Split

SplitNSource

pub struct SplitN

The pieces of Regex::splitn.

Trait implementations 1
  • impl Iterator for SplitN

NoExpandSource

pub struct NoExpand(pub str)

A replacement used as is: $ has no meaning in it.

nabi
use regex::{NoExpand, Regex};

let re = try Regex::new("x");
assert(re.replace_all("axb", NoExpand("$1")) == "a$1b");
Trait implementations 1

RegexSetSource

pub struct RegexSet

A set of patterns matched together: which of them match h, in one linear pass however many there are.

nabi
use regex::RegexSet;

let set = try RegexSet::new([r"\d+", r"[a-z]+", r"^x"]);
let m = set.matches("abc 42");
assert(m.matched(0) && m.matched(1) && !m.matched(2));
assert(m.iter() == [0, 1]);
  • pub fn new(patterns: List<str>) throws (RegexError) -> RegexSet§

    Source

    Compiles every pattern of patterns with the default options. An error names the pattern by its position in the message.

    nabi
    let bad = try { _ = try regex::RegexSet::new(["a", "("]); "" } catch e: regex::RegexError { f"{e}" };
    assert(bad.contains("unclosed group"));
    
  • pub fn is_match(self, h: str) -> bool§

    Source

    Whether any pattern matches h.

    nabi
    let set = try regex::RegexSet::new([r"^\d+$", "x"]);
    assert(set.is_match("123") && !set.is_match("12a"));
    
  • pub fn matches(self, h: str) -> SetMatches§

    Source

    Which patterns match h.

    nabi
    let set = try regex::RegexSet::new(["foo", "bar", "baz"]);
    assert(set.matches("foobaz").iter() == [0, 2]);
    
  • pub fn len(self) -> usize§

    Source

    The number of patterns.

    nabi
    assert((try regex::RegexSet::new(["a", "b"])).len() == 2);
    
  • pub fn patterns(self) -> List<str>§

    Source

    The patterns as written.

    nabi
    assert((try regex::RegexSet::new(["a+", "b"])).patterns() == ["a+", "b"]);
    

SetMatchesSource

pub struct SetMatches

Which patterns of a RegexSet matched.

  • pub fn matched(self, i: usize) -> bool§

    Source

    Whether pattern i matched.

    nabi
    let set = try regex::RegexSet::new(["a", "b"]);
    assert(set.matches("b").matched(1));
    
  • pub fn matched_any(self) -> bool§

    Source

    Whether any pattern matched.

    nabi
    let set = try regex::RegexSet::new(["a", "b"]);
    assert(!set.matches("c").matched_any());
    
  • pub fn iter(self) -> List<usize>§

    Source

    The indexes of the patterns that matched, ascending.

    nabi
    let set = try regex::RegexSet::new(["a", "b", "c"]);
    assert(set.matches("ca").iter() == [0, 2]);
    
  • pub fn len(self) -> usize§

    Source

    The number of patterns in the set.

    nabi
    assert((try regex::RegexSet::new(["a", "b"])).matches("").len() == 2);
    

Enums

RegexErrorSource

pub enum RegexError

What went wrong building a regex.

nabi
use regex::{Regex, RegexError};

let e = try {
    _ = try Regex::new("(ab");
    ""
} catch e: RegexError { f"{e}" };
assert(e.contains("unclosed group"));
  • Syntax§

    Source

    The pattern does not parse. at is the byte offset in pattern where the problem starts.

  • TooBig§

    Source

    The compiled program would exceed the size limit.

  • pub const fn position(self) -> usize | none§

    Source

    The byte offset of a syntax error in the pattern, none for a size error.

    nabi
    let e = try { _ = try regex::Regex::new("a)"); 0 } catch e: regex::RegexError { e.position() ?? 99 };
    assert(e == 1);
    
Trait implementations 2
  • impl Display for RegexError
  • impl Error for RegexError

Traits

ReplacerSource

pub trait Replacer

What Regex::replace puts in place of each match. str is a template ($1, ${name}, $$; see Captures::expand), NoExpand a literal, and a fn(Captures) -> str computes it.

nabi
use regex::{Captures, Regex};

let re = try Regex::new(r"\d+");
let doubled = re.replace_all("3 apples, 12 pears", |c: Captures| f"{(try! c[0].parse::<i64>()) * 2}");
assert(doubled == "6 apples, 24 pears");
  • fn append(self, caps: Captures, dst: StrBuf)§

    Source

    Appends the replacement for the match caps to dst.

  • fn fixed(self) -> str | none§

    Source

    The replacement when it is the same for every match, so the groups need not be found.

Functions

escapeSource

pub fn escape(text: str) -> str

text with every regex metacharacter escaped, so it matches itself.

nabi
let p = regex::escape("1.5*(x)");
assert(p == r"1\.5\*\(x\)");
assert((try regex::Regex::new(p)).is_match("a 1.5*(x)"));

Constants

DEFAULT_DFA_SIZE_LIMITSource

pub const DEFAULT_DFA_SIZE_LIMIT: usize = 2097152

Default limit of each lazy DFA cache, in bytes.

DEFAULT_SIZE_LIMITSource

pub const DEFAULT_SIZE_LIMIT: usize = 10485760

Default limit of a compiled program, in bytes.

UNICODE_VERSIONSource

pub const UNICODE_VERSION: str = "18.0.0"

The Unicode version of the tables.