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