2This crate provides routines for searching strings for matches of a [regular
3expression] (aka "regex"). The regex syntax supported by this crate is similar
4to other regex engines, but it lacks several features that are not known how to
5implement efficiently. This includes, but is not limited to, look-around and
6backreferences. In exchange, all regex searches in this crate have worst case
7`O(m * n)` time complexity, where `m` is proportional to the size of the regex
8and `n` is proportional to the size of the string being searched.
10[regular expression]: https://en.wikipedia.org/wiki/Regular_expression
12If you just want API documentation, then skip to the [`Regex`] type. Otherwise,
13here's a quick example showing one way of parsing the output of a grep-like
17use regex::Regex;
19let re = Regex::new(r"(?m)^([^:]+):([0-9]+):(.+)$").unwrap();
20let hay = "\
21path/to/foo:54:Blue Harvest
22path/to/bar:90:Something, Something, Something, Dark Side
23path/to/baz:3:It's a Trap!
26let mut results = vec![];
27for (_, [path, lineno, line]) in re.captures_iter(hay).map(|c| c.extract()) {
28 results.push((path, lineno.parse::<u64>()?, line));
30assert_eq!(results, vec![
31 ("path/to/foo", 54, "Blue Harvest"),
32 ("path/to/bar", 90, "Something, Something, Something, Dark Side"),
33 ("path/to/baz", 3, "It's a Trap!"),
35# Ok::<(), Box<dyn std::error::Error>>(())
38# Overview
40The primary type in this crate is a [`Regex`]. Its most important methods are
41as follows:
43* [`Regex::new`] compiles a regex using the default configuration. A
44[`RegexBuilder`] permits setting a non-default configuration. (For example,
45case insensitive matching, verbose mode and others.)
46* [`Regex::is_match`] reports whether a match exists in a particular haystack.
47* [`Regex::find`] reports the byte offsets of a match in a haystack, if one
48exists. [`Regex::find_iter`] returns an iterator over all such matches.
49* [`Regex::captures`] returns a [`Captures`], which reports both the byte
50offsets of a match in a haystack and the byte offsets of each matching capture
51group from the regex in the haystack.
52[`Regex::captures_iter`] returns an iterator over all such matches.
54There is also a [`RegexSet`], which permits searching for multiple regex
55patterns simultaneously in a single search. However, it currently only reports
56which patterns match and *not* the byte offsets of a match.
58Otherwise, this top-level crate documentation is organized as follows:
60* [Usage](#usage) shows how to add the `regex` crate to your Rust project.
61* [Examples](#examples) provides a limited selection of regex search examples.
62* [Performance](#performance) provides a brief summary of how to optimize regex
63searching speed.
64* [Unicode](#unicode) discusses support for non-ASCII patterns.
65* [Syntax](#syntax) enumerates the specific regex syntax supported by this
67* [Untrusted input](#untrusted-input) discusses how this crate deals with regex
68patterns or haystacks that are untrusted.
69* [Crate features](#crate-features) documents the Cargo features that can be
70enabled or disabled for this crate.
71* [Other crates](#other-crates) links to other crates in the `regex` family.
73# Usage
75The `regex` crate is [on crates.io](https://crates.io/crates/regex) and can be
76used by adding `regex` to your dependencies in your project's `Cargo.toml`.
77Or more simply, just run `cargo add regex`.
79Here is a complete example that creates a new Rust project, adds a dependency
80on `regex`, creates the source code for a regex search and then runs the
83First, create the project in a new directory:
86$ mkdir regex-example
87$ cd regex-example
88$ cargo init
91Second, add a dependency on `regex`:
94$ cargo add regex
97Third, edit `src/main.rs`. Delete what's there and replace it with this:
100use regex::Regex;
102fn main() {
103 let re = Regex::new(r"Hello (?<name>\w+)!").unwrap();
104 let Some(caps) = re.captures("Hello Murphy!") else {
105 println!("no match!");
106 return;
107 };
108 println!("The name is: {}", &caps["name"]);
112Fourth, run it with `cargo run`:
115$ cargo run
116 Compiling memchr v2.5.0
117 Compiling regex-syntax v0.7.1
118 Compiling aho-corasick v1.0.1
119 Compiling regex v1.8.1
120 Compiling regex-example v0.1.0 (/tmp/regex-example)
121 Finished dev [unoptimized + debuginfo] target(s) in 4.22s
122 Running `target/debug/regex-example`
123The name is: Murphy
126The first time you run the program will show more output like above. But
127subsequent runs shouldn't have to re-compile the dependencies.
129# Examples
131This section provides a few examples, in tutorial style, showing how to
132search a haystack with a regex. There are more examples throughout the API
135Before starting though, it's worth defining a few terms:
137* A **regex** is a Rust value whose type is `Regex`. We use `re` as a
138variable name for a regex.
139* A **pattern** is the string that is used to build a regex. We use `pat` as
140a variable name for a pattern.
141* A **haystack** is the string that is searched by a regex. We use `hay` as a
142variable name for a haystack.
144Sometimes the words "regex" and "pattern" are used interchangeably.
146General use of regular expressions in this crate proceeds by compiling a
147**pattern** into a **regex**, and then using that regex to search, split or
148replace parts of a **haystack**.
150### Example: find a middle initial
152We'll start off with a very simple example: a regex that looks for a specific
153name but uses a wildcard to match a middle initial. Our pattern serves as
154something like a template that will match a particular name with *any* middle
158use regex::Regex;
160// We use 'unwrap()' here because it would be a bug in our program if the
161// pattern failed to compile to a regex. Panicking in the presence of a bug
162// is okay.
163let re = Regex::new(r"Homer (.)\. Simpson").unwrap();
164let hay = "Homer J. Simpson";
165let Some(caps) = re.captures(hay) else { return };
166assert_eq!("J", &caps[1]);
169There are a few things worth noticing here in our first example:
171* The `.` is a special pattern meta character that means "match any single
172character except for new lines." (More precisely, in this crate, it means
173"match any UTF-8 encoding of any Unicode scalar value other than `\n`.")
174* We can match an actual `.` literally by escaping it, i.e., `\.`.
175* We use Rust's [raw strings] to avoid needing to deal with escape sequences in
176both the regex pattern syntax and in Rust's string literal syntax. If we didn't
177use raw strings here, we would have had to use `\\.` to match a literal `.`
178character. That is, `r"\."` and `"\\."` are equivalent patterns.
179* We put our wildcard `.` instruction in parentheses. These parentheses have a
180special meaning that says, "make whatever part of the haystack matches within
181these parentheses available as a capturing group." After finding a match, we
182access this capture group with `&caps[1]`.
184[raw strings]: https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals
186Otherwise, we execute a search using `re.captures(hay)` and return from our
187function if no match occurred. We then reference the middle initial by asking
188for the part of the haystack that matched the capture group indexed at `1`.
189(The capture group at index 0 is implicit and always corresponds to the entire
190match. In this case, that's `Homer J. Simpson`.)
192### Example: named capture groups
194Continuing from our middle initial example above, we can tweak the pattern
195slightly to give a name to the group that matches the middle initial:
198use regex::Regex;
200// Note that (?P<middle>.) is a different way to spell the same thing.
201let re = Regex::new(r"Homer (?<middle>.)\. Simpson").unwrap();
202let hay = "Homer J. Simpson";
203let Some(caps) = re.captures(hay) else { return };
204assert_eq!("J", &caps["middle"]);
207Giving a name to a group can be useful when there are multiple groups in
208a pattern. It makes the code referring to those groups a bit easier to
211### Example: validating a particular date format
213This examples shows how to confirm whether a haystack, in its entirety, matches
214a particular date format:
217use regex::Regex;
219let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
223Notice the use of the `^` and `$` anchors. In this crate, every regex search is
224run with an implicit `(?s:.)*?` at the beginning of its pattern, which allows
225the regex to match anywhere in a haystack. Anchors, as above, can be used to
226ensure that the full haystack matches a pattern.
228This crate is also Unicode aware by default, which means that `\d` might match
229more than you might expect it to. For example:
232use regex::Regex;
234let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
238To only match an ASCII decimal digit, all of the following are equivalent:
240* `[0-9]`
241* `(?-u:\d)`
242* `[[:digit:]]`
243* `[\d&&\p{ascii}]`
245### Example: finding dates in a haystack
247In the previous example, we showed how one might validate that a haystack,
248in its entirety, corresponded to a particular date format. But what if we wanted
249to extract all things that look like dates in a specific format from a haystack?
250To do this, we can use an iterator API to find all matches (notice that we've
251removed the anchors and switched to looking for ASCII-only digits):
254use regex::Regex;
256let re = Regex::new(r"[0-9]{4}-[0-9]{2}-[0-9]{2}").unwrap();
257let hay = "What do 1865-04-14, 1881-07-02, 1901-09-06 and 1963-11-22 have in common?";
258// 'm' is a 'Match', and 'as_str()' returns the matching part of the haystack.
259let dates: Vec<&str> = re.find_iter(hay).map(|m| m.as_str()).collect();
260assert_eq!(dates, vec![
261 "1865-04-14",
262 "1881-07-02",
263 "1901-09-06",
264 "1963-11-22",
268We can also iterate over [`Captures`] values instead of [`Match`] values, and
269that in turn permits accessing each component of the date via capturing groups:
272use regex::Regex;
274let re = Regex::new(r"(?<y>[0-9]{4})-(?<m>[0-9]{2})-(?<d>[0-9]{2})").unwrap();
275let hay = "What do 1865-04-14, 1881-07-02, 1901-09-06 and 1963-11-22 have in common?";
276// 'm' is a 'Match', and 'as_str()' returns the matching part of the haystack.
277let dates: Vec<(&str, &str, &str)> = re.captures_iter(hay).map(|caps| {
278 // The unwraps are okay because every capture group must match if the whole
279 // regex matches, and in this context, we know we have a match.
280 //
281 // Note that we use `caps.name("y").unwrap().as_str()` instead of
282 // `&caps["y"]` because the lifetime of the former is the same as the
283 // lifetime of `hay` above, but the lifetime of the latter is tied to the
284 // lifetime of `caps` due to how the `Index` trait is defined.
285 let year = caps.name("y").unwrap().as_str();
286 let month = caps.name("m").unwrap().as_str();
287 let day = caps.name("d").unwrap().as_str();
288 (year, month, day)
290assert_eq!(dates, vec![
291 ("1865", "04", "14"),
292 ("1881", "07", "02"),
293 ("1901", "09", "06"),
294 ("1963", "11", "22"),
298### Example: simpler capture group extraction
300One can use [`Captures::extract`] to make the code from the previous example a
301bit simpler in this case:
304use regex::Regex;
306let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
307let hay = "What do 1865-04-14, 1881-07-02, 1901-09-06 and 1963-11-22 have in common?";
308let dates: Vec<(&str, &str, &str)> = re.captures_iter(hay).map(|caps| {
309 let (_, [year, month, day]) = caps.extract();
310 (year, month, day)
312assert_eq!(dates, vec![
313 ("1865", "04", "14"),
314 ("1881", "07", "02"),
315 ("1901", "09", "06"),
316 ("1963", "11", "22"),
320`Captures::extract` works by ensuring that the number of matching groups match
321the number of groups requested via the `[year, month, day]` syntax. If they do,
322then the substrings for each corresponding capture group are automatically
323returned in an appropriately sized array. Rust's syntax for pattern matching
324arrays does the rest.
326### Example: replacement with named capture groups
328Building on the previous example, perhaps we'd like to rearrange the date
329formats. This can be done by finding each match and replacing it with
330something different. The [`Regex::replace_all`] routine provides a convenient
331way to do this, including by supporting references to named groups in the
332replacement string:
335use regex::Regex;
337let re = Regex::new(r"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})").unwrap();
338let before = "1973-01-05, 1975-08-25 and 1980-10-18";
339let after = re.replace_all(before, "$m/$d/$y");
340assert_eq!(after, "01/05/1973, 08/25/1975 and 10/18/1980");
343The replace methods are actually polymorphic in the replacement, which
344provides more flexibility than is seen here. (See the documentation for
345[`Regex::replace`] for more details.)
347### Example: verbose mode
349When your regex gets complicated, you might consider using something other
350than regex. But if you stick with regex, you can use the `x` flag to enable
351insignificant whitespace mode or "verbose mode." In this mode, whitespace
352is treated as insignificant and one may write comments. This may make your
353patterns easier to comprehend.
356use regex::Regex;
358let re = Regex::new(r"(?x)
359 (?P<y>\d{4}) # the year, including all Unicode digits
360 -
361 (?P<m>\d{2}) # the month, including all Unicode digits
362 -
363 (?P<d>\d{2}) # the day, including all Unicode digits
366let before = "1973-01-05, 1975-08-25 and 1980-10-18";
367let after = re.replace_all(before, "$m/$d/$y");
368assert_eq!(after, "01/05/1973, 08/25/1975 and 10/18/1980");
371If you wish to match against whitespace in this mode, you can still use `\s`,
372`\n`, `\t`, etc. For escaping a single space character, you can escape it
373directly with `\ `, use its hex character code `\x20` or temporarily disable
374the `x` flag, e.g., `(?-x: )`.
376### Example: match multiple regular expressions simultaneously
378This demonstrates how to use a [`RegexSet`] to match multiple (possibly
379overlapping) regexes in a single scan of a haystack:
382use regex::RegexSet;
384let set = RegexSet::new(&[
385 r"\w+",
386 r"\d+",
387 r"\pL+",
388 r"foo",
389 r"bar",
390 r"barfoo",
391 r"foobar",
394// Iterate over and collect all of the matches. Each match corresponds to the
395// ID of the matching pattern.
396let matches: Vec<_> = set.matches("foobar").into_iter().collect();
397assert_eq!(matches, vec![0, 2, 3, 4, 6]);
399// You can also test whether a particular regex matched:
400let matches = set.matches("foobar");
405# Performance
407This section briefly discusses a few concerns regarding the speed and resource
408usage of regexes.
410### Only ask for what you need
412When running a search with a regex, there are generally three different types
413of information one can ask for:
4151. Does a regex match in a haystack?
4162. Where does a regex match in a haystack?
4173. Where do each of the capturing groups match in a haystack?
419Generally speaking, this crate could provide a function to answer only #3,
420which would subsume #1 and #2 automatically. However, it can be significantly
421more expensive to compute the location of capturing group matches, so it's best
422not to do it if you don't need to.
424Therefore, only ask for what you need. For example, don't use [`Regex::find`]
425if you only need to test if a regex matches a haystack. Use [`Regex::is_match`]
428### Unicode can impact memory usage and search speed
430This crate has first class support for Unicode and it is **enabled by default**.
431In many cases, the extra memory required to support it will be negligible and
432it typically won't impact search speed. But it can in some cases.
434With respect to memory usage, the impact of Unicode principally manifests
435through the use of Unicode character classes. Unicode character classes
436tend to be quite large. For example, `\w` by default matches around 140,000
437distinct codepoints. This requires additional memory, and tends to slow down
438regex compilation. While a `\w` here and there is unlikely to be noticed,
439writing `\w{100}` will for example result in quite a large regex by default.
440Indeed, `\w` is considerably larger than its ASCII-only version, so if your
441requirements are satisfied by ASCII, it's probably a good idea to stick to
442ASCII classes. The ASCII-only version of `\w` can be spelled in a number of
443ways. All of the following are equivalent:
445* `[0-9A-Za-z_]`
446* `(?-u:\w)`
447* `[[:word:]]`
448* `[\w&&\p{ascii}]`
450With respect to search speed, Unicode tends to be handled pretty well, even when
451using large Unicode character classes. However, some of the faster internal
452regex engines cannot handle a Unicode aware word boundary assertion. So if you
453don't need Unicode-aware word boundary assertions, you might consider using
454`(?-u:\b)` instead of `\b`, where the former uses an ASCII-only definition of
455a word character.
457### Literals might accelerate searches
459This crate tends to be quite good at recognizing literals in a regex pattern
460and using them to accelerate a search. If it is at all possible to include
461some kind of literal in your pattern, then it might make search substantially
462faster. For example, in the regex `\w+@\w+`, the engine will look for
463occurrences of `@` and then try a reverse match for `\w+` to find the start
466### Avoid re-compiling regexes, especially in a loop
468It is an anti-pattern to compile the same pattern in a loop since regex
469compilation is typically expensive. (It takes anywhere from a few microseconds
470to a few **milliseconds** depending on the size of the pattern.) Not only is
471compilation itself expensive, but this also prevents optimizations that reuse
472allocations internally to the regex engine.
474In Rust, it can sometimes be a pain to pass regexes around if they're used from
475inside a helper function. Instead, we recommend using crates like [`once_cell`]
476and [`lazy_static`] to ensure that patterns are compiled exactly once.
478[`once_cell`]: https://crates.io/crates/once_cell
479[`lazy_static`]: https://crates.io/crates/lazy_static
481This example shows how to use `once_cell`:
484use {
485 once_cell::sync::Lazy,
486 regex::Regex,
489fn some_helper_function(haystack: &str) -> bool {
490 static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"...").unwrap());
491 RE.is_match(haystack)
494fn main() {
495 assert!(some_helper_function("abc"));
496 assert!(!some_helper_function("ac"));
500Specifically, in this example, the regex will be compiled when it is used for
501the first time. On subsequent uses, it will reuse the previously built `Regex`.
502Notice how one can define the `Regex` locally to a specific function.
504### Sharing a regex across threads can result in contention
506While a single `Regex` can be freely used from multiple threads simultaneously,
507there is a small synchronization cost that must be paid. Generally speaking,
508one shouldn't expect to observe this unless the principal task in each thread
509is searching with the regex *and* most searches are on short haystacks. In this
510case, internal contention on shared resources can spike and increase latency,
511which in turn may slow down each individual search.
513One can work around this by cloning each `Regex` before sending it to another
514thread. The cloned regexes will still share the same internal read-only portion
515of its compiled state (it's reference counted), but each thread will get
516optimized access to the mutable space that is used to run a search. In general,
517there is no additional cost in memory to doing this. The only cost is the added
518code complexity required to explicitly clone the regex. (If you share the same
519`Regex` across multiple threads, each thread still gets its own mutable space,
520but accessing that space is slower.)
522# Unicode
524This section discusses what kind of Unicode support this regex library has.
525Before showing some examples, we'll summarize the relevant points:
527* This crate almost fully implements "Basic Unicode Support" (Level 1) as
528specified by the [Unicode Technical Standard #18][UTS18]. The full details
529of what is supported are documented in [UNICODE.md] in the root of the regex
530crate repository. There is virtually no support for "Extended Unicode Support"
531(Level 2) from UTS#18.
532* The top-level [`Regex`] runs searches *as if* iterating over each of the
533codepoints in the haystack. That is, the fundamental atom of matching is a
534single codepoint.
535* [`bytes::Regex`], in contrast, permits disabling Unicode mode for part of all
536of your pattern in all cases. When Unicode mode is disabled, then a search is
537run *as if* iterating over each byte in the haystack. That is, the fundamental
538atom of matching is a single byte. (A top-level `Regex` also permits disabling
539Unicode and thus matching *as if* it were one byte at a time, but only when
540doing so wouldn't permit matching invalid UTF-8.)
541* When Unicode mode is enabled (the default), `.` will match an entire Unicode
542scalar value, even when it is encoded using multiple bytes. When Unicode mode
543is disabled (e.g., `(?-u:.)`), then `.` will match a single byte in all cases.
544* The character classes `\w`, `\d` and `\s` are all Unicode-aware by default.
545Use `(?-u:\w)`, `(?-u:\d)` and `(?-u:\s)` to get their ASCII-only definitions.
546* Similarly, `\b` and `\B` use a Unicode definition of a "word" character.
547To get ASCII-only word boundaries, use `(?-u:\b)` and `(?-u:\B)`. This also
548applies to the special word boundary assertions. (That is, `\b{start}`,
549`\b{end}`, `\b{start-half}`, `\b{end-half}`.)
550* `^` and `$` are **not** Unicode-aware in multi-line mode. Namely, they only
551recognize `\n` (assuming CRLF mode is not enabled) and not any of the other
552forms of line terminators defined by Unicode.
553* Case insensitive searching is Unicode-aware and uses simple case folding.
554* Unicode general categories, scripts and many boolean properties are available
555by default via the `\p{property name}` syntax.
556* In all cases, matches are reported using byte offsets. Or more precisely,
557UTF-8 code unit offsets. This permits constant time indexing and slicing of the
560[UTS18]: https://unicode.org/reports/tr18/
561[UNICODE.md]: https://github.com/rust-lang/regex/blob/master/UNICODE.md
563Patterns themselves are **only** interpreted as a sequence of Unicode scalar
564values. This means you can use Unicode characters directly in your pattern:
567use regex::Regex;
569let re = Regex::new(r"(?i)Δ+").unwrap();
570let m = re.find("ΔδΔ").unwrap();
571assert_eq!((0, 6), (m.start(), m.end()));
572// alternatively:
573assert_eq!(0..6, m.range());
576As noted above, Unicode general categories, scripts, script extensions, ages
577and a smattering of boolean properties are available as character classes. For
578example, you can match a sequence of numerals, Greek or Cherokee letters:
581use regex::Regex;
583let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap();
584let m = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap();
585assert_eq!(3..23, m.range());
588While not specific to Unicode, this library also supports character class set
589operations. Namely, one can nest character classes arbitrarily and perform set
590operations on them. Those set operations are union (the default), intersection,
591difference and symmetric difference. These set operations tend to be most
592useful with Unicode character classes. For example, to match any codepoint
593that is both in the `Greek` script and in the `Letter` general category:
596use regex::Regex;
598let re = Regex::new(r"[\p{Greek}&&\pL]+").unwrap();
599let subs: Vec<&str> = re.find_iter("ΔδΔ𐅌ΔδΔ").map(|m| m.as_str()).collect();
600assert_eq!(subs, vec!["ΔδΔ", "ΔδΔ"]);
602// If we just matches on Greek, then all codepoints would match!
603let re = Regex::new(r"\p{Greek}+").unwrap();
604let subs: Vec<&str> = re.find_iter("ΔδΔ𐅌ΔδΔ").map(|m| m.as_str()).collect();
605assert_eq!(subs, vec!["ΔδΔ𐅌ΔδΔ"]);
608### Opt out of Unicode support
610The [`bytes::Regex`] type that can be used to search `&[u8]` haystacks. By
611default, haystacks are conventionally treated as UTF-8 just like it is with the
612main `Regex` type. However, this behavior can be disabled by turning off the
613`u` flag, even if doing so could result in matching invalid UTF-8. For example,
614when the `u` flag is disabled, `.` will match any byte instead of any Unicode
615scalar value.
617Disabling the `u` flag is also possible with the standard `&str`-based `Regex`
618type, but it is only allowed where the UTF-8 invariant is maintained. For
619example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an
620`&str`-based `Regex`, but `(?-u:\W)` will attempt to match *any byte* that
621isn't in `(?-u:\w)`, which in turn includes bytes that are invalid UTF-8.
622Similarly, `(?-u:\xFF)` will attempt to match the raw byte `\xFF` (instead of
623`U+00FF`), which is invalid UTF-8 and therefore is illegal in `&str`-based
626Finally, since Unicode support requires bundling large Unicode data
627tables, this crate exposes knobs to disable the compilation of those
628data tables, which can be useful for shrinking binary size and reducing
629compilation times. For details on how to do that, see the section on [crate
632# Syntax
634The syntax supported in this crate is documented below.
636Note that the regular expression parser and abstract syntax are exposed in
637a separate crate, [`regex-syntax`](https://docs.rs/regex-syntax).
639### Matching one character
641<pre class="rust">
642. any character except new line (includes new line with s flag)
643[0-9] any ASCII digit
644\d digit (\p{Nd})
645\D not digit
646\pX Unicode character class identified by a one-letter name
647\p{Greek} Unicode character class (general category or script)
648\PX Negated Unicode character class identified by a one-letter name
649\P{Greek} negated Unicode character class (general category or script)
652### Character classes
654<pre class="rust">
655[xyz] A character class matching either x, y or z (union).
656[^xyz] A character class matching any character except x, y and z.
657[a-z] A character class matching any character in range a-z.
658[[:alpha:]] ASCII character class ([A-Za-z])
659[[:^alpha:]] Negated ASCII character class ([^A-Za-z])
660[x[^xyz]] Nested/grouping character class (matching any character except y and z)
661[a-y&&xyz] Intersection (matching x or y)
662[0-9&&[^4]] Subtraction using intersection and negation (matching 0-9 except 4)
663[0-9--4] Direct subtraction (matching 0-9 except 4)
664[a-g~~b-h] Symmetric difference (matching `a` and `h` only)
665[\[\]] Escaping in character classes (matching [ or ])
666[a&&b] An empty character class matching nothing
669Any named character class may appear inside a bracketed `[...]` character
670class. For example, `[\p{Greek}[:digit:]]` matches any ASCII digit or any
671codepoint in the `Greek` script. `[\p{Greek}&&\pL]` matches Greek letters.
673Precedence in character classes, from most binding to least:
6751. Ranges: `[a-cd]` == `[[a-c]d]`
6762. Union: `[ab&&bc]` == `[[ab]&&[bc]]`
6773. Intersection, difference, symmetric difference. All three have equivalent
678precedence, and are evaluated in left-to-right order. For example,
679`[\pL--\p{Greek}&&\p{Uppercase}]` == `[[\pL--\p{Greek}]&&\p{Uppercase}]`.
6804. Negation: `[^a-z&&b]` == `[^[a-z&&b]]`.
682### Composites
684<pre class="rust">
685xy concatenation (x followed by y)
686x|y alternation (x or y, prefer x)
689This example shows how an alternation works, and what it means to prefer a
690branch in the alternation over subsequent branches.
693use regex::Regex;
695let haystack = "samwise";
696// If 'samwise' comes first in our alternation, then it is
697// preferred as a match, even if the regex engine could
698// technically detect that 'sam' led to a match earlier.
699let re = Regex::new(r"samwise|sam").unwrap();
700assert_eq!("samwise", re.find(haystack).unwrap().as_str());
701// But if 'sam' comes first, then it will match instead.
702// In this case, it is impossible for 'samwise' to match
703// because 'sam' is a prefix of it.
704let re = Regex::new(r"sam|samwise").unwrap();
705assert_eq!("sam", re.find(haystack).unwrap().as_str());
708### Repetitions
710<pre class="rust">
711x* zero or more of x (greedy)
712x+ one or more of x (greedy)
713x? zero or one of x (greedy)
714x*? zero or more of x (ungreedy/lazy)
715x+? one or more of x (ungreedy/lazy)
716x?? zero or one of x (ungreedy/lazy)
717x{n,m} at least n x and at most m x (greedy)
718x{n,} at least n x (greedy)
719x{n} exactly n x
720x{n,m}? at least n x and at most m x (ungreedy/lazy)
721x{n,}? at least n x (ungreedy/lazy)
722x{n}? exactly n x
725### Empty matches
727<pre class="rust">
728^ the beginning of a haystack (or start-of-line with multi-line mode)
729$ the end of a haystack (or end-of-line with multi-line mode)
730\A only the beginning of a haystack (even with multi-line mode enabled)
731\z only the end of a haystack (even with multi-line mode enabled)
732\b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
733\B not a Unicode word boundary
734\b{start}, \< a Unicode start-of-word boundary (\W|\A on the left, \w on the right)
735\b{end}, \> a Unicode end-of-word boundary (\w on the left, \W|\z on the right))
736\b{start-half} half of a Unicode start-of-word boundary (\W|\A on the left)
737\b{end-half} half of a Unicode end-of-word boundary (\W|\z on the right)
740The empty regex is valid and matches the empty string. For example, the
741empty regex matches `abc` at positions `0`, `1`, `2` and `3`. When using the
742top-level [`Regex`] on `&str` haystacks, an empty match that splits a codepoint
743is guaranteed to never be returned. However, such matches are permitted when
744using a [`bytes::Regex`]. For example:
747let re = regex::Regex::new(r"").unwrap();
748let ranges: Vec<_> = re.find_iter("💩").map(|m| m.range()).collect();
749assert_eq!(ranges, vec![0..0, 4..4]);
751let re = regex::bytes::Regex::new(r"").unwrap();
752let ranges: Vec<_> = re.find_iter("💩".as_bytes()).map(|m| m.range()).collect();
753assert_eq!(ranges, vec![0..0, 1..1, 2..2, 3..3, 4..4]);
756Note that an empty regex is distinct from a regex that can never match.
757For example, the regex `[a&&b]` is a character class that represents the
758intersection of `a` and `b`. That intersection is empty, which means the
759character class is empty. Since nothing is in the empty set, `[a&&b]` matches
760nothing, not even the empty string.
762### Grouping and flags
764<pre class="rust">
765(exp) numbered capture group (indexed by opening parenthesis)
766(?P<name>exp) named (also numbered) capture group (names must be alpha-numeric)
767(?<name>exp) named (also numbered) capture group (names must be alpha-numeric)
768(?:exp) non-capturing group
769(?flags) set flags within current group
770(?flags:exp) set flags for exp (non-capturing)
773Capture group names must be any sequence of alpha-numeric Unicode codepoints,
774in addition to `.`, `_`, `[` and `]`. Names must start with either an `_` or
775an alphabetic codepoint. Alphabetic codepoints correspond to the `Alphabetic`
776Unicode property, while numeric codepoints correspond to the union of the
777`Decimal_Number`, `Letter_Number` and `Other_Number` general categories.
779Flags are each a single character. For example, `(?x)` sets the flag `x`
780and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
781the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
782the `x` flag and clears the `y` flag.
784All flags are by default disabled unless stated otherwise. They are:
786<pre class="rust">
787i case-insensitive: letters match both upper and lower case
788m multi-line mode: ^ and $ match begin/end of line
789s allow . to match \n
790R enables CRLF mode: when multi-line mode is enabled, \r\n is used
791U swap the meaning of x* and x*?
792u Unicode support (enabled by default)
793x verbose mode, ignores whitespace and allow line comments (starting with `#`)
796Note that in verbose mode, whitespace is ignored everywhere, including within
797character classes. To insert whitespace, use its escaped form or a hex literal.
798For example, `\ ` or `\x20` for an ASCII space.
800Flags can be toggled within a pattern. Here's an example that matches
801case-insensitively for the first part but case-sensitively for the second part:
804use regex::Regex;
806let re = Regex::new(r"(?i)a+(?-i)b+").unwrap();
807let m = re.find("AaAaAbbBBBb").unwrap();
808assert_eq!(m.as_str(), "AaAaAbb");
811Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
814Multi-line mode means `^` and `$` no longer match just at the beginning/end of
815the input, but also at the beginning/end of lines:
818use regex::Regex;
820let re = Regex::new(r"(?m)^line \d+").unwrap();
821let m = re.find("line one\nline 2\n").unwrap();
822assert_eq!(m.as_str(), "line 2");
825Note that `^` matches after new lines, even at the end of input:
828use regex::Regex;
830let re = Regex::new(r"(?m)^").unwrap();
831let m = re.find_iter("test\n").last().unwrap();
832assert_eq!((m.start(), m.end()), (5, 5));
835When both CRLF mode and multi-line mode are enabled, then `^` and `$` will
836match either `\r` and `\n`, but never in the middle of a `\r\n`:
839use regex::Regex;
841let re = Regex::new(r"(?mR)^foo$").unwrap();
842let m = re.find("\r\nfoo\r\n").unwrap();
843assert_eq!(m.as_str(), "foo");
846Unicode mode can also be selectively disabled, although only when the result
847*would not* match invalid UTF-8. One good example of this is using an ASCII
848word boundary instead of a Unicode word boundary, which might make some regex
849searches run faster:
852use regex::Regex;
854let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap();
855let m = re.find("$$abc$$").unwrap();
856assert_eq!(m.as_str(), "abc");
859### Escape sequences
861Note that this includes all possible escape sequences, even ones that are
862documented elsewhere.
864<pre class="rust">
865\* literal *, applies to all ASCII except [0-9A-Za-z<>]
866\a bell (\x07)
867\f form feed (\x0C)
868\t horizontal tab
869\n new line
870\r carriage return
871\v vertical tab (\x0B)
872\A matches at the beginning of a haystack
873\z matches at the end of a haystack
874\b word boundary assertion
875\B negated word boundary assertion
876\b{start}, \< start-of-word boundary assertion
877\b{end}, \> end-of-word boundary assertion
878\b{start-half} half of a start-of-word boundary assertion
879\b{end-half} half of a end-of-word boundary assertion
880\123 octal character code, up to three digits (when enabled)
881\x7F hex character code (exactly two digits)
882\x{10FFFF} any hex character code corresponding to a Unicode code point
883\u007F hex character code (exactly four digits)
884\u{7F} any hex character code corresponding to a Unicode code point
885\U0000007F hex character code (exactly eight digits)
886\U{7F} any hex character code corresponding to a Unicode code point
887\p{Letter} Unicode character class
888\P{Letter} negated Unicode character class
889\d, \s, \w Perl character class
890\D, \S, \W negated Perl character class
893### Perl character classes (Unicode friendly)
895These classes are based on the definitions provided in
898<pre class="rust">
899\d digit (\p{Nd})
900\D not digit
901\s whitespace (\p{White_Space})
902\S not whitespace
903\w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
904\W not word character
907### ASCII character classes
909These classes are based on the definitions provided in
912<pre class="rust">
913[[:alnum:]] alphanumeric ([0-9A-Za-z])
914[[:alpha:]] alphabetic ([A-Za-z])
915[[:ascii:]] ASCII ([\x00-\x7F])
916[[:blank:]] blank ([\t ])
917[[:cntrl:]] control ([\x00-\x1F\x7F])
918[[:digit:]] digits ([0-9])
919[[:graph:]] graphical ([!-~])
920[[:lower:]] lower case ([a-z])
921[[:print:]] printable ([ -~])
922[[:punct:]] punctuation ([!-/:-@\[-`{-~])
923[[:space:]] whitespace ([\t\n\v\f\r ])
924[[:upper:]] upper case ([A-Z])
925[[:word:]] word characters ([0-9A-Za-z_])
926[[:xdigit:]] hex digit ([0-9A-Fa-f])
929# Untrusted input
931This crate is meant to be able to run regex searches on untrusted haystacks
932without fear of [ReDoS]. This crate also, to a certain extent, supports
933untrusted patterns.
935[ReDoS]: https://en.wikipedia.org/wiki/ReDoS
937This crate differs from most (but not all) other regex engines in that it
938doesn't use unbounded backtracking to run a regex search. In those cases,
939one generally cannot use untrusted patterns *or* untrusted haystacks because
940it can be very difficult to know whether a particular pattern will result in
941catastrophic backtracking or not.
943We'll first discuss how this crate deals with untrusted inputs and then wrap
944it up with a realistic discussion about what practice really looks like.
946### Panics
948Outside of clearly documented cases, most APIs in this crate are intended to
949never panic regardless of the inputs given to them. For example, `Regex::new`,
950`Regex::is_match`, `Regex::find` and `Regex::captures` should never panic. That
951is, it is an API promise that those APIs will never panic no matter what inputs
952are given to them. With that said, regex engines are complicated beasts, and
953providing a rock solid guarantee that these APIs literally never panic is
954essentially equivalent to saying, "there are no bugs in this library." That is
955a bold claim, and not really one that can be feasibly made with a straight
958Don't get the wrong impression here. This crate is extensively tested, not just
959with unit and integration tests, but also via fuzz testing. For example, this
960crate is part of the [OSS-fuzz project]. Panics should be incredibly rare, but
961it is possible for bugs to exist, and thus possible for a panic to occur. If
962you need a rock solid guarantee against panics, then you should wrap calls into
963this library with [`std::panic::catch_unwind`].
965It's also worth pointing out that this library will *generally* panic when
966other regex engines would commit undefined behavior. When undefined behavior
967occurs, your program might continue as if nothing bad has happened, but it also
968might mean your program is open to the worst kinds of exploits. In contrast,
969the worst thing a panic can do is a denial of service.
971[OSS-fuzz project]: https://android.googlesource.com/platform/external/oss-fuzz/+/refs/tags/android-t-preview-1/projects/rust-regex/
972[`std::panic::catch_unwind`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
974### Untrusted patterns
976The principal way this crate deals with them is by limiting their size by
977default. The size limit can be configured via [`RegexBuilder::size_limit`]. The
978idea of a size limit is that compiling a pattern into a `Regex` will fail if it
979becomes "too big." Namely, while *most* resources consumed by compiling a regex
980are approximately proportional (albeit with some high constant factors in some
981cases, such as with Unicode character classes) to the length of the pattern
982itself, there is one particular exception to this: counted repetitions. Namely,
983this pattern:
989Is equivalent to this pattern:
995In both of these cases, the actual pattern string is quite small, but the
996resulting `Regex` value is quite large. Indeed, as the first pattern shows,
997it isn't enough to locally limit the size of each repetition because they can
998be stacked in a way that results in exponential growth.
1000To provide a bit more context, a simplified view of regex compilation looks
1001like this:
1003* The pattern string is parsed into a structured representation called an AST.
1004Counted repetitions are not expanded and Unicode character classes are not
1005looked up in this stage. That is, the size of the AST is proportional to the
1006size of the pattern with "reasonable" constant factors. In other words, one
1007can reasonably limit the memory used by an AST by limiting the length of the
1008pattern string.
1009* The AST is translated into an HIR. Counted repetitions are still *not*
1010expanded at this stage, but Unicode character classes are embedded into the
1011HIR. The memory usage of a HIR is still proportional to the length of the
1012original pattern string, but the constant factors---mostly as a result of
1013Unicode character classes---can be quite high. Still though, the memory used by
1014an HIR can be reasonably limited by limiting the length of the pattern string.
1015* The HIR is compiled into a [Thompson NFA]. This is the stage at which
1016something like `\w{5}` is rewritten to `\w\w\w\w\w`. Thus, this is the stage
1017at which [`RegexBuilder::size_limit`] is enforced. If the NFA exceeds the
1018configured size, then this stage will fail.
1020[Thompson NFA]: https://en.wikipedia.org/wiki/Thompson%27s_construction
1022The size limit helps avoid two different kinds of exorbitant resource usage:
1024* It avoids permitting exponential memory usage based on the size of the
1025pattern string.
1026* It avoids long search times. This will be discussed in more detail in the
1027next section, but worst case search time *is* dependent on the size of the
1028regex. So keeping regexes limited to a reasonable size is also a way of keeping
1029search times reasonable.
1031Finally, it's worth pointing out that regex compilation is guaranteed to take
1032worst case `O(m)` time, where `m` is proportional to the size of regex. The
1033size of the regex here is *after* the counted repetitions have been expanded.
1035**Advice for those using untrusted regexes**: limit the pattern length to
1036something small and expand it as needed. Configure [`RegexBuilder::size_limit`]
1037to something small and then expand it as needed.
1039### Untrusted haystacks
1041The main way this crate guards against searches from taking a long time is by
1042using algorithms that guarantee a `O(m * n)` worst case time and space bound.
1045* `m` is proportional to the size of the regex, where the size of the regex
1046includes the expansion of all counted repetitions. (See the previous section on
1047untrusted patterns.)
1048* `n` is proportional to the length, in bytes, of the haystack.
1050In other words, if you consider `m` to be a constant (for example, the regex
1051pattern is a literal in the source code), then the search can be said to run
1052in "linear time." Or equivalently, "linear time with respect to the size of the
1055But the `m` factor here is important not to ignore. If a regex is
1056particularly big, the search times can get quite slow. This is why, in part,
1057[`RegexBuilder::size_limit`] exists.
1059**Advice for those searching untrusted haystacks**: As long as your regexes
1060are not enormous, you should expect to be able to search untrusted haystacks
1061without fear. If you aren't sure, you should benchmark it. Unlike backtracking
1062engines, if your regex is so big that it's likely to result in slow searches,
1063this is probably something you'll be able to observe regardless of what the
1064haystack is made up of.
1066### Iterating over matches
1068One thing that is perhaps easy to miss is that the worst case time
1069complexity bound of `O(m * n)` applies to methods like [`Regex::is_match`],
1070[`Regex::find`] and [`Regex::captures`]. It does **not** apply to
1071[`Regex::find_iter`] or [`Regex::captures_iter`]. Namely, since iterating over
1072all matches can execute many searches, and each search can scan the entire
1073haystack, the worst case time complexity for iterators is `O(m * n^2)`.
1075One example of where this occurs is when a pattern consists of an alternation,
1076where an earlier branch of the alternation requires scanning the entire
1077haystack only to discover that there is no match. It also requires a later
1078branch of the alternation to have matched at the beginning of the search. For
1079example, consider the pattern `.*[^A-Z]|[A-Z]` and the haystack `AAAAA`. The
1080first search will scan to the end looking for matches of `.*[^A-Z]` even though
1081a finite automata engine (as in this crate) knows that `[A-Z]` has already
1082matched the first character of the haystack. This is due to the greedy nature
1083of regex searching. That first search will report a match at the first `A` only
1084after scanning to the end to discover that no other match exists. The next
1085search then begins at the second `A` and the behavior repeats.
1087There is no way to avoid this. This means that if both patterns and haystacks
1088are untrusted and you're iterating over all matches, you're susceptible to
1089worst case quadratic time complexity. One possible way to mitigate this
1090is to drop down to the lower level `regex-automata` crate and use its
1091`meta::Regex` iterator APIs. There, you can configure the search to operate
1092in "earliest" mode by passing a `Input::new(haystack).earliest(true)` to
1093`meta::Regex::find_iter` (for example). By enabling this mode, you give up
1094the normal greedy match semantics of regex searches and instead ask the regex
1095engine to immediately stop as soon as a match has been found. Enabling this
1096mode will thus restore the worst case `O(m * n)` time complexity bound, but at
1097the cost of different semantics.
1099### Untrusted inputs in practice
1101While providing a `O(m * n)` worst case time bound on all searches goes a long
1102way toward preventing [ReDoS], that doesn't mean every search you can possibly
1103run will complete without burning CPU time. In general, there are a few ways
1104for the `m * n` time bound to still bite you:
1106* You are searching an exceptionally long haystack. No matter how you slice
1107it, a longer haystack will take more time to search. This crate may often make
1108very quick work of even long haystacks because of its literal optimizations,
1109but those aren't available for all regexes.
1110* Unicode character classes can cause searches to be quite slow in some cases.
1111This is especially true when they are combined with counted repetitions. While
1112the regex size limit above will protect you from the most egregious cases,
1113the default size limit still permits pretty big regexes that can execute more
1114slowly than one might expect.
1115* While routines like [`Regex::find`] and [`Regex::captures`] guarantee
1116worst case `O(m * n)` search time, routines like [`Regex::find_iter`] and
1117[`Regex::captures_iter`] actually have worst case `O(m * n^2)` search time.
1118This is because `find_iter` runs many searches, and each search takes worst
1119case `O(m * n)` time. Thus, iteration of all matches in a haystack has
1120worst case `O(m * n^2)`. A good example of a pattern that exhibits this is
1121`(?:A+){1000}|` or even `.*[^A-Z]|[A-Z]`.
1123In general, unstrusted haystacks are easier to stomach than untrusted patterns.
1124Untrusted patterns give a lot more control to the caller to impact the
1125performance of a search. In many cases, a regex search will actually execute in
1126average case `O(n)` time (i.e., not dependent on the size of the regex), but
1127this can't be guaranteed in general. Therefore, permitting untrusted patterns
1128means that your only line of defense is to put a limit on how big `m` (and
1129perhaps also `n`) can be in `O(m * n)`. `n` is limited by simply inspecting
1130the length of the haystack while `m` is limited by *both* applying a limit to
1131the length of the pattern *and* a limit on the compiled size of the regex via
1134It bears repeating: if you're accepting untrusted patterns, it would be a good
1135idea to start with conservative limits on `m` and `n`, and then carefully
1136increase them as needed.
1138# Crate features
1140By default, this crate tries pretty hard to make regex matching both as fast
1141as possible and as correct as it can be. This means that there is a lot of
1142code dedicated to performance, the handling of Unicode data and the Unicode
1143data itself. Overall, this leads to more dependencies, larger binaries and
1144longer compile times. This trade off may not be appropriate in all cases, and
1145indeed, even when all Unicode and performance features are disabled, one is
1146still left with a perfectly serviceable regex engine that will work well in
1147many cases. (Note that code is not arbitrarily reducible, and for this reason,
1148the [`regex-lite`](https://docs.rs/regex-lite) crate exists to provide an even
1149more minimal experience by cutting out Unicode and performance, but still
1150maintaining the linear search time bound.)
1152This crate exposes a number of features for controlling that trade off. Some
1153of these features are strictly performance oriented, such that disabling them
1154won't result in a loss of functionality, but may result in worse performance.
1155Other features, such as the ones controlling the presence or absence of Unicode
1156data, can result in a loss of functionality. For example, if one disables the
1157`unicode-case` feature (described below), then compiling the regex `(?i)a`
1158will fail since Unicode case insensitivity is enabled by default. Instead,
1159callers must use `(?i-u)a` to disable Unicode case folding. Stated differently,
1160enabling or disabling any of the features below can only add or subtract from
1161the total set of valid regular expressions. Enabling or disabling a feature
1162will never modify the match semantics of a regular expression.
1164Most features below are enabled by default. Features that aren't enabled by
1165default are noted.
1167### Ecosystem features
1169* **std** -
1170 When enabled, this will cause `regex` to use the standard library. In terms
1171 of APIs, `std` causes error types to implement the `std::error::Error`
1172 trait. Enabling `std` will also result in performance optimizations,
1173 including SIMD and faster synchronization primitives. Notably, **disabling
1174 the `std` feature will result in the use of spin locks**. To use a regex
1175 engine without `std` and without spin locks, you'll need to drop down to
1176 the [`regex-automata`](https://docs.rs/regex-automata) crate.
1177* **logging** -
1178 When enabled, the `log` crate is used to emit messages about regex
1179 compilation and search strategies. This is **disabled by default**. This is
1180 typically only useful to someone working on this crate's internals, but might
1181 be useful if you're doing some rabbit hole performance hacking. Or if you're
1182 just interested in the kinds of decisions being made by the regex engine.
1184### Performance features
1186* **perf** -
1187 Enables all performance related features except for `perf-dfa-full`. This
1188 feature is enabled by default is intended to cover all reasonable features
1189 that improve performance, even if more are added in the future.
1190* **perf-dfa** -
1191 Enables the use of a lazy DFA for matching. The lazy DFA is used to compile
1192 portions of a regex to a very fast DFA on an as-needed basis. This can
1193 result in substantial speedups, usually by an order of magnitude on large
1194 haystacks. The lazy DFA does not bring in any new dependencies, but it can
1195 make compile times longer.
1196* **perf-dfa-full** -
1197 Enables the use of a full DFA for matching. Full DFAs are problematic because
1198 they have worst case `O(2^n)` construction time. For this reason, when this
1199 feature is enabled, full DFAs are only used for very small regexes and a
1200 very small space bound is used during determinization to avoid the DFA
1201 from blowing up. This feature is not enabled by default, even as part of
1202 `perf`, because it results in fairly sizeable increases in binary size and
1203 compilation time. It can result in faster search times, but they tend to be
1204 more modest and limited to non-Unicode regexes.
1205* **perf-onepass** -
1206 Enables the use of a one-pass DFA for extracting the positions of capture
1207 groups. This optimization applies to a subset of certain types of NFAs and
1208 represents the fastest engine in this crate for dealing with capture groups.
1209* **perf-backtrack** -
1210 Enables the use of a bounded backtracking algorithm for extracting the
1211 positions of capture groups. This usually sits between the slowest engine
1212 (the PikeVM) and the fastest engine (one-pass DFA) for extracting capture
1213 groups. It's used whenever the regex is not one-pass and is small enough.
1214* **perf-inline** -
1215 Enables the use of aggressive inlining inside match routines. This reduces
1216 the overhead of each match. The aggressive inlining, however, increases
1217 compile times and binary size.
1218* **perf-literal** -
1219 Enables the use of literal optimizations for speeding up matches. In some
1220 cases, literal optimizations can result in speedups of _several_ orders of
1221 magnitude. Disabling this drops the `aho-corasick` and `memchr` dependencies.
1222* **perf-cache** -
1223 This feature used to enable a faster internal cache at the cost of using
1224 additional dependencies, but this is no longer an option. A fast internal
1225 cache is now used unconditionally with no additional dependencies. This may
1226 change in the future.
1228### Unicode features
1230* **unicode** -
1231 Enables all Unicode features. This feature is enabled by default, and will
1232 always cover all Unicode features, even if more are added in the future.
1233* **unicode-age** -
1234 Provide the data for the
1235 [Unicode `Age` property](https://www.unicode.org/reports/tr44/tr44-24.html#Character_Age).
1236 This makes it possible to use classes like `\p{Age:6.0}` to refer to all
1237 codepoints first introduced in Unicode 6.0
1238* **unicode-bool** -
1239 Provide the data for numerous Unicode boolean properties. The full list
1240 is not included here, but contains properties like `Alphabetic`, `Emoji`,
1241 `Lowercase`, `Math`, `Uppercase` and `White_Space`.
1242* **unicode-case** -
1243 Provide the data for case insensitive matching using
1244 [Unicode's "simple loose matches" specification](https://www.unicode.org/reports/tr18/#Simple_Loose_Matches).
1245* **unicode-gencat** -
1246 Provide the data for
1247 [Unicode general categories](https://www.unicode.org/reports/tr44/tr44-24.html#General_Category_Values).
1248 This includes, but is not limited to, `Decimal_Number`, `Letter`,
1249 `Math_Symbol`, `Number` and `Punctuation`.
1250* **unicode-perl** -
1251 Provide the data for supporting the Unicode-aware Perl character classes,
1252 corresponding to `\w`, `\s` and `\d`. This is also necessary for using
1253 Unicode-aware word boundary assertions. Note that if this feature is
1254 disabled, the `\s` and `\d` character classes are still available if the
1255 `unicode-bool` and `unicode-gencat` features are enabled, respectively.
1256* **unicode-script** -
1257 Provide the data for
1258 [Unicode scripts and script extensions](https://www.unicode.org/reports/tr24/).
1259 This includes, but is not limited to, `Arabic`, `Cyrillic`, `Hebrew`,
1260 `Latin` and `Thai`.
1261* **unicode-segment** -
1262 Provide the data necessary to provide the properties used to implement the
1263 [Unicode text segmentation algorithms](https://www.unicode.org/reports/tr29/).
1264 This enables using classes like `\p{gcb=Extend}`, `\p{wb=Katakana}` and
1265 `\p{sb=ATerm}`.
1267# Other crates
1269This crate has two required dependencies and several optional dependencies.
1270This section briefly describes them with the goal of raising awareness of how
1271different components of this crate may be used independently.
1273It is somewhat unusual for a regex engine to have dependencies, as most regex
1274libraries are self contained units with no dependencies other than a particular
1275environment's standard library. Indeed, for other similarly optimized regex
1276engines, most or all of the code in the dependencies of this crate would
1277normally just be unseparable or coupled parts of the crate itself. But since
1278Rust and its tooling ecosystem make the use of dependencies so easy, it made
1279sense to spend some effort de-coupling parts of this crate and making them
1280independently useful.
1282We only briefly describe each crate here.
1284* [`regex-lite`](https://docs.rs/regex-lite) is not a dependency of `regex`,
1285but rather, a standalone zero-dependency simpler version of `regex` that
1286prioritizes compile times and binary size. In exchange, it eschews Unicode
1287support and performance. Its match semantics are as identical as possible to
1288the `regex` crate, and for the things it supports, its APIs are identical to
1289the APIs in this crate. In other words, for a lot of use cases, it is a drop-in
1291* [`regex-syntax`](https://docs.rs/regex-syntax) provides a regular expression
1292parser via `Ast` and `Hir` types. It also provides routines for extracting
1293literals from a pattern. Folks can use this crate to do analysis, or even to
1294build their own regex engine without having to worry about writing a parser.
1295* [`regex-automata`](https://docs.rs/regex-automata) provides the regex engines
1296themselves. One of the downsides of finite automata based regex engines is that
1297they often need multiple internal engines in order to have similar or better
1298performance than an unbounded backtracking engine in practice. `regex-automata`
1299in particular provides public APIs for a PikeVM, a bounded backtracker, a
1300one-pass DFA, a lazy DFA, a fully compiled DFA and a meta regex engine that
1301combines all them together. It also has native multi-pattern support and
1302provides a way to compile and serialize full DFAs such that they can be loaded
1303and searched in a no-std no-alloc environment. `regex-automata` itself doesn't
1304even have a required dependency on `regex-syntax`!
1305* [`memchr`](https://docs.rs/memchr) provides low level SIMD vectorized
1306routines for quickly finding the location of single bytes or even substrings
1307in a haystack. In other words, it provides fast `memchr` and `memmem` routines.
1308These are used by this crate in literal optimizations.
1309* [`aho-corasick`](https://docs.rs/aho-corasick) provides multi-substring
1310search. It also provides SIMD vectorized routines in the case where the number
1311of substrings to search for is relatively small. The `regex` crate also uses
1312this for literal optimizations.
1317#![cfg_attr(feature = "pattern", feature(pattern))]
1323extern crate alloc;
1324#[cfg(any(test, feature = "std"))]
1325extern crate std;
1327pub use crate::error::Error;
1329pub use crate::{builders::string::*, regex::string::*, regexset::string::*};
1331mod builders;
1332pub mod bytes;
1333mod error;
1334mod find_byte;
1335#[cfg(feature = "pattern")]
1336mod pattern;
1337mod regex;
1338mod regexset;
1340/// Escapes all regular expression meta characters in `pattern`.
1342/// The string returned may be safely used as a literal in a regular
1343/// expression.
1344pub fn escape(pattern: &str) -> alloc::string::String {
1345 regex_syntax::escape(pattern)