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.
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:
use regex::regex!;
for line in ["id=7", "id=x"] {
if regex!(r"^id=\d+$").is_match(line) { println(line); }
}
Structs
CapturesSource
pub struct CapturesThe 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.
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);
Group
i, ornonewhen it did not take part or does not exist.nabilet c = (try regex::Regex::new("(a)|(b)")).captures("b")?; assert(c.get(1) == none && c.get(2)?.as_str() == "b" && c.get(7) == none);The group named
name, ornone.nabilet c = (try regex::Regex::new(r"(?<n>\d+)")).captures("a42")?; assert(c.name("n")?.as_str() == "42" && c.name("m") == none);The number of groups, group 0 included (also those that did not take part).
nabiassert((try regex::Regex::new("(a)(b)?")).captures("a")?.len() == 3);Every group in order.
nabilet 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", "-"]);templatewith$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}afor group 1 followed bya.nabilet 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 Capturesimpl Index<str> for Capturesimpl Debug for Captures
MatchSource
pub struct MatchOne match: a span of the haystack, in byte offsets on char
boundaries.
let re = try regex::Regex::new("b+");
let m = re.find("abbc")?;
assert(m.range() == (1..3) && m.len() == 2 && !m.is_empty());
The byte offset where the match starts.
nabiassert((try regex::Regex::new("c")).find("abc")?.start() == 2);The byte offset just past the match.
nabiassert((try regex::Regex::new("c")).find("abc")?.end() == 3);start()..end().nabiassert((try regex::Regex::new("é")).find("café")?.range() == (3..5));The length in bytes.
nabiassert((try regex::Regex::new("é+")).find("éé")?.len() == 4);Whether the match is empty.
nabiassert((try regex::Regex::new("x*")).find("abc")?.is_empty() ?? false);The matched text.
nabiassert((try regex::Regex::new(r"\d+")).find("ab12c")?.as_str() == "12");
Trait implementations 1
impl Display for Match
CaptureMatchesSource
pub struct CaptureMatchesThe groups of each match of Regex::captures_iter.
Trait implementations 1
impl Iterator for CaptureMatches
MatchesSource
pub struct MatchesThe matches of Regex::find_iter.
Trait implementations 1
impl Iterator for Matches
RegexSource
pub struct RegexA 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.
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");
Sourcepub fn new(§pattern: str) throws (RegexError) -> Regex Compiles
patternwith the default options.nabilet re = try regex::Regex::new(r"\bcat\b"); assert(re.is_match("a cat sat") && !re.is_match("concat"));The pattern as written.
nabiassert((try regex::Regex::new("a|b")).as_str() == "a|b");Whether the regex matches anywhere in
h.nabilet re = try regex::Regex::new(r"\d+"); assert(re.is_match("abc123") && !re.is_match("abc"));is_matchfor a search starting at bytestart(a char boundary); the text beforestartstill counts for^and\b.nabilet re = try regex::Regex::new(r"\bb"); assert(!re.is_match_at("ab", 1));The end of the first match the engine sees, which may be shorter than the one
findreports; the cheapest search afteris_match.nabilet re = try regex::Regex::new("a+"); assert(re.shortest_match("baaa")? == 2);shortest_matchfrom bytestart.nabilet re = try regex::Regex::new("a+"); assert(re.shortest_match_at("aba", 1)? == 3);The leftmost-first match in
h.nabilet 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");findfrom bytestart(a char boundary); the text beforestartstill counts for^and\b.nabilet re = try regex::Regex::new("a"); assert(re.find_at("aXa", 1)?.start() == 2);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).nabilet 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"]);The groups of the leftmost-first match.
nabilet 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");capturesfrom bytestart.nabilet re = try regex::Regex::new(r"(\d)"); assert(re.captures_at("1 2", 1)?[1] == "2");
Sourcepub fn captures_iter(§self, h: str) -> CaptureMatches The groups of every match, left to right (the matches of
find_iter).nabilet 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"]);The pieces of
hbetween matches. A match at either end gives an empty piece there.nabilet re = try regex::Regex::new(r"[,;]\s*"); let parts: List<str> = re.split("a, b;c").collect(); assert(parts == ["a", "b", "c"]);At most
limitpieces ofsplit; the last holds the rest ofhunsplit.nabilet re = try regex::Regex::new(","); let parts: List<str> = re.splitn("a,b,c", 2).collect(); assert(parts == ["a", "b,c"]);The number of groups, group 0 (the whole match) included.
nabiassert((try regex::Regex::new("(a)(?:b)(c)")).captures_len() == 3);Each group's name,
nonefor unnamed ones; group 0 first.nabilet re = try regex::Regex::new("(?<a>x)(y)"); assert(re.capture_names() == [none, "a", none]);hwith the first match replaced byrep.nabilet re = try regex::Regex::new(r"(\w+)@(\w+)"); assert(re.replace("mail ann@home now", "$2 at $1") == "mail home at ann now");hwith every match replaced byrep.nabilet re = try regex::Regex::new(r"\s+"); assert(re.replace_all("a b \t c", " ") == "a b c");hwith the firstlimitmatches replaced byrep;limit0 replaces all of them.nabilet re = try regex::Regex::new("a"); assert(re.replacen("aaaa", 2, "b") == "bbaa");
Trait implementations 2
impl Display for Regeximpl Debug for Regex
RegexBuilderSource
pub struct RegexBuilderOptions for building a Regex. Each flag here sets the default that
inline flags such as (?i) can still change.
use regex::RegexBuilder;
let re = try RegexBuilder::new("^hello$").case_insensitive(true).multi_line(true).build();
assert(re.is_match("say\nHELLO\n"));
A builder for
patternwith the default options.nabilet re = try regex::RegexBuilder::new("a+").build(); assert(re.is_match("caaat"));Letters match their other cases (Unicode simple case folding), as with
(?i).nabilet re = try regex::RegexBuilder::new("straße").case_insensitive(true).build(); assert(re.is_match("STRAßE"));^and$match at line starts and ends too, as with(?m).nabilet re = try regex::RegexBuilder::new("^b").multi_line(true).build(); assert(re.is_match("a\nb"));.matches\ntoo, as with(?s).nabilet re = try regex::RegexBuilder::new("a.b").dot_matches_new_line(true).build(); assert(re.is_match("a\nb"));Greedy and lazy repetition trade places, as with
(?U).nabilet re = try regex::RegexBuilder::new("a+").swap_greed(true).build(); assert(re.find("aaa")?.as_str() == "a");Whitespace in the pattern is ignored and
#starts a comment, as with(?x).nabilet re = try regex::RegexBuilder::new("a b # comment").ignore_whitespace(true).build(); assert(re.is_match("ab"));Unicode-aware
\w,\d,\s,\band case folding (on by default); off, they are ASCII only, as with(?-u).nabilet re = try regex::RegexBuilder::new(r"^\w$").unicode(false).build(); assert(re.is_match("a") && !re.is_match("é"));The most bytes the compiled program may take (10 MiB by default); a larger pattern fails with
RegexError::TooBig.nabilet r = try { _ = try regex::RegexBuilder::new(r"\w{100}").size_limit(1000).build(); true } catch _: regex::RegexError { false }; assert(!r);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.
nabilet re = try regex::RegexBuilder::new("[a-z]+").dfa_size_limit(4096).build(); assert(re.is_match("abc"));
Sourcepub fn build(§self) throws (RegexError) -> Regex Compiles the pattern.
nabilet ok = try { _ = try regex::RegexBuilder::new("(").build(); true } catch _: regex::RegexError { false }; assert(!ok);
SplitSource
pub struct SplitThe pieces of Regex::split.
Trait implementations 1
impl Iterator for Split
SplitNSource
pub struct SplitNThe 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.
use regex::{NoExpand, Regex};
let re = try Regex::new("x");
assert(re.replace_all("axb", NoExpand("$1")) == "a$1b");
Trait implementations 1
impl Replacer for NoExpand
RegexSetSource
pub struct RegexSetA set of patterns matched together: which of them match h, in one
linear pass however many there are.
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]);
Sourcepub fn new(§patterns: List<str>) throws (RegexError) -> RegexSet Compiles every pattern of
patternswith the default options. An error names the pattern by its position in the message.nabilet bad = try { _ = try regex::RegexSet::new(["a", "("]); "" } catch e: regex::RegexError { f"{e}" }; assert(bad.contains("unclosed group"));Whether any pattern matches
h.nabilet set = try regex::RegexSet::new([r"^\d+$", "x"]); assert(set.is_match("123") && !set.is_match("12a"));
Sourcepub fn matches(§self, h: str) -> SetMatches Which patterns match
h.nabilet set = try regex::RegexSet::new(["foo", "bar", "baz"]); assert(set.matches("foobaz").iter() == [0, 2]);The number of patterns.
nabiassert((try regex::RegexSet::new(["a", "b"])).len() == 2);The patterns as written.
nabiassert((try regex::RegexSet::new(["a+", "b"])).patterns() == ["a+", "b"]);
SetMatchesSource
pub struct SetMatchesWhich patterns of a RegexSet matched.
Whether pattern
imatched.nabilet set = try regex::RegexSet::new(["a", "b"]); assert(set.matches("b").matched(1));Whether any pattern matched.
nabilet set = try regex::RegexSet::new(["a", "b"]); assert(!set.matches("c").matched_any());The indexes of the patterns that matched, ascending.
nabilet set = try regex::RegexSet::new(["a", "b", "c"]); assert(set.matches("ca").iter() == [0, 2]);The number of patterns in the set.
nabiassert((try regex::RegexSet::new(["a", "b"])).matches("").len() == 2);
Enums
RegexErrorSource
pub enum RegexErrorWhat went wrong building a regex.
use regex::{Regex, RegexError};
let e = try {
_ = try Regex::new("(ab");
""
} catch e: RegexError { f"{e}" };
assert(e.contains("unclosed group"));
The pattern does not parse.
atis the byte offset inpatternwhere the problem starts.The compiled program would exceed the size limit.
The byte offset of a syntax error in the pattern,
nonefor a size error.nabilet e = try { _ = try regex::Regex::new("a)"); 0 } catch e: regex::RegexError { e.position() ?? 99 }; assert(e == 1);
Trait implementations 2
impl Display for RegexErrorimpl Error for RegexError
Traits
ReplacerSource
pub trait ReplacerWhat 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.
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");
Appends the replacement for the match
capstodst.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.
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 = 2097152Default limit of each lazy DFA cache, in bytes.
DEFAULT_SIZE_LIMITSource
pub const DEFAULT_SIZE_LIMIT: usize = 10485760Default limit of a compiled program, in bytes.
UNICODE_VERSIONSource
pub const UNICODE_VERSION: str = "18.0.0"The Unicode version of the tables.