Debian Codegraph @

debian/rust-vendor/regex/src/lib.rs

raw
1 /*!
2 This crate provides routines for searching strings for matches of a [regular
3 expression] (aka "regex"). The regex syntax supported by this crate is similar
4 to other regex engines, but it lacks several features that are not known how to
5 implement efficiently. This includes, but is not limited to, look-around and
6 backreferences. 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
8 and `n` is proportional to the size of the string being searched.
9
10 [regular expression]: https://en.wikipedia.org/wiki/Regular_expression
11
12 If you just want API documentation, then skip to the [`Regex`] type. Otherwise,
13 here's a quick example showing one way of parsing the output of a grep-like
14 program:
15
16 ```rust
17 use regex::Regex;
18
19 let re = Regex::new(r"(?m)^([^:]+):([0-9]+):(.+)$").unwrap();
20 let hay = "\
21 path/to/foo:54:Blue Harvest
22 path/to/bar:90:Something, Something, Something, Dark Side
23 path/to/baz:3:It's a Trap!
24 ";
25
26 let mut results = vec![];
27 for (_, [path, lineno, line]) in re.captures_iter(hay).map(|c| c.extract()) {
28 results.push((path, lineno.parse::<u64>()?, line));
29 }
30 assert_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
38 Or, make use of the [`regex!`](crate::regex) macro to compile the regex once
39 and re-use that same regex automatically. This is useful inside functions.
40 For example:
41
42 ```rust
43 use regex::regex;
44
45 fn 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
53 let hay = "\
54 path/to/foo:54:Blue Harvest
55 path/to/bar:90:Something, Something, Something, Dark Side
56 path/to/baz:3:It's a Trap!
57 ";
58
59 let matches = hay.lines().filter(|line| is_match(line)).count();
60 assert_eq!(matches, 2);
61 ```
62
63 # Overview
64
65 The primary type in this crate is a [`Regex`]. Its most important methods are
66 as follows:
67
68 * [`Regex::new`] compiles a regex using the default configuration. A
69 [`RegexBuilder`] permits setting a non-default configuration. (For example,
70 case 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
73 exists. [`Regex::find_iter`] returns an iterator over all such matches.
74 * [`Regex::captures`] returns a [`Captures`], which reports both the byte
75 offsets of a match in a haystack and the byte offsets of each matching capture
76 group from the regex in the haystack.
77 [`Regex::captures_iter`] returns an iterator over all such matches.
78
79 There is also a [`RegexSet`], which permits searching for multiple regex
80 patterns simultaneously in a single search. However, it currently only reports
81 which patterns match and *not* the byte offsets of a match.
82
83 Otherwise, 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
88 searching speed.
89 * [Unicode](#unicode) discusses support for non-ASCII patterns.
90 * [Syntax](#syntax) enumerates the specific regex syntax supported by this
91 crate.
92 * [Untrusted input](#untrusted-input) discusses how this crate deals with regex
93 patterns or haystacks that are untrusted.
94 * [Crate features](#crate-features) documents the Cargo features that can be
95 enabled or disabled for this crate.
96 * [Other crates](#other-crates) links to other crates in the `regex` family.
97
98 # Usage
99
100 The `regex` crate is [on crates.io](https://crates.io/crates/regex) and can be
101 used by adding `regex` to your dependencies in your project's `Cargo.toml`.
102 Or more simply, just run `cargo add regex`.
103
104 Here is a complete example that creates a new Rust project, adds a dependency
105 on `regex`, creates the source code for a regex search and then runs the
106 program.
107
108 First, create the project in a new directory:
109
110 ```text
111 $ mkdir regex-example
112 $ cd regex-example
113 $ cargo init
114 ```
115
116 Second, add a dependency on `regex`:
117
118 ```text
119 $ cargo add regex
120 ```
121
122 Third, edit `src/main.rs`. Delete what's there and replace it with this:
123
124 ```
125 use regex::Regex;
126
127 fn 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
137 Fourth, 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`
148 The name is: Murphy
149 ```
150
151 The first time you run the program will show more output like above. But
152 subsequent runs shouldn't have to re-compile the dependencies.
153
154 # Examples
155
156 This section provides a few examples, in tutorial style, showing how to
157 search a haystack with a regex. There are more examples throughout the API
158 documentation.
159
160 Before 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
163 variable name for a regex.
164 * A **pattern** is the string that is used to build a regex. We use `pat` as
165 a variable name for a pattern.
166 * A **haystack** is the string that is searched by a regex. We use `hay` as a
167 variable name for a haystack.
168
169 Sometimes the words "regex" and "pattern" are used interchangeably.
170
171 General 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
173 replace parts of a **haystack**.
174
175 ### Example: find a middle initial
176
177 We'll start off with a very simple example: a regex that looks for a specific
178 name but uses a wildcard to match a middle initial. Our pattern serves as
179 something like a template that will match a particular name with *any* middle
180 initial.
181
182 ```rust
183 use 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.
188 let re = Regex::new(r"Homer (.)\. Simpson").unwrap();
189 let hay = "Homer J. Simpson";
190 let Some(caps) = re.captures(hay) else { return };
191 assert_eq!("J", &caps[1]);
192 ```
193
194 There 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
197 character 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
201 both the regex pattern syntax and in Rust's string literal syntax. If we didn't
202 use raw strings here, we would have had to use `\\.` to match a literal `.`
203 character. That is, `r"\."` and `"\\."` are equivalent patterns.
204 * We put our wildcard `.` instruction in parentheses. These parentheses have a
205 special meaning that says, "make whatever part of the haystack matches within
206 these parentheses available as a capturing group." After finding a match, we
207 access this capture group with `&caps[1]`.
208
209 [raw strings]: https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals
210
211 Otherwise, we execute a search using `re.captures(hay)` and return from our
212 function if no match occurred. We then reference the middle initial by asking
213 for 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
215 match. In this case, that's `Homer J. Simpson`.)
216
217 ### Example: named capture groups
218
219 Continuing from our middle initial example above, we can tweak the pattern
220 slightly to give a name to the group that matches the middle initial:
221
222 ```rust
223 use regex::Regex;
224
225 // Note that (?P<middle>.) is a different way to spell the same thing.
226 let re = Regex::new(r"Homer (?<middle>.)\. Simpson").unwrap();
227 let hay = "Homer J. Simpson";
228 let Some(caps) = re.captures(hay) else { return };
229 assert_eq!("J", &caps["middle"]);
230 ```
231
232 Giving a name to a group can be useful when there are multiple groups in
233 a pattern. It makes the code referring to those groups a bit easier to
234 understand.
235
236 ### Example: validating a particular date format
237
238 This examples shows how to confirm whether a haystack, in its entirety, matches
239 a particular date format:
240
241 ```rust
242 use regex::Regex;
243
244 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
245 assert!(re.is_match("2010-03-14"));
246 ```
247
248 Notice the use of the `^` and `$` anchors. In this crate, every regex search is
249 run with an implicit `(?s:.)*?` at the beginning of its pattern, which allows
250 the regex to match anywhere in a haystack. Anchors, as above, can be used to
251 ensure that the full haystack matches a pattern.
252
253 This crate is also Unicode aware by default, which means that `\d` might match
254 more than you might expect it to. For example:
255
256 ```rust
257 use regex::Regex;
258
259 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
260 assert!(re.is_match("𝟚𝟘𝟙𝟘-𝟘𝟛-𝟙𝟜"));
261 ```
262
263 To 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
272 In the previous example, we showed how one might validate that a haystack,
273 in its entirety, corresponded to a particular date format. But what if we wanted
274 to extract all things that look like dates in a specific format from a haystack?
275 To do this, we can use an iterator API to find all matches (notice that we've
276 removed the anchors and switched to looking for ASCII-only digits):
277
278 ```rust
279 use regex::Regex;
280
281 let re = Regex::new(r"[0-9]{4}-[0-9]{2}-[0-9]{2}").unwrap();
282 let 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.
284 let dates: Vec<&str> = re.find_iter(hay).map(|m| m.as_str()).collect();
285 assert_eq!(dates, vec![
286 "1865-04-14",
287 "1881-07-02",
288 "1901-09-06",
289 "1963-11-22",
290 ]);
291 ```
292
293 We can also iterate over [`Captures`] values instead of [`Match`] values, and
294 that in turn permits accessing each component of the date via capturing groups:
295
296 ```rust
297 use regex::Regex;
298
299 let re = Regex::new(r"(?<y>[0-9]{4})-(?<m>[0-9]{2})-(?<d>[0-9]{2})").unwrap();
300 let 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.
302 let 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();
315 assert_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
325 One can use [`Captures::extract`] to make the code from the previous example a
326 bit simpler in this case:
327
328 ```rust
329 use regex::Regex;
330
331 let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
332 let hay = "What do 1865-04-14, 1881-07-02, 1901-09-06 and 1963-11-22 have in common?";
333 let dates: Vec<(&str, &str, &str)> = re.captures_iter(hay).map(|caps| {
334 let (_, [year, month, day]) = caps.extract();
335 (year, month, day)
336 }).collect();
337 assert_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
346 the number of groups requested via the `[year, month, day]` syntax. If they do,
347 then the substrings for each corresponding capture group are automatically
348 returned in an appropriately sized array. Rust's syntax for pattern matching
349 arrays does the rest.
350
351 ### Example: replacement with named capture groups
352
353 Building on the previous example, perhaps we'd like to rearrange the date
354 formats. This can be done by finding each match and replacing it with
355 something different. The [`Regex::replace_all`] routine provides a convenient
356 way to do this, including by supporting references to named groups in the
357 replacement string:
358
359 ```rust
360 use regex::Regex;
361
362 let re = Regex::new(r"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})").unwrap();
363 let before = "1973-01-05, 1975-08-25 and 1980-10-18";
364 let after = re.replace_all(before, "$m/$d/$y");
365 assert_eq!(after, "01/05/1973, 08/25/1975 and 10/18/1980");
366 ```
367
368 The replace methods are actually polymorphic in the replacement, which
369 provides more flexibility than is seen here. (See the documentation for
370 [`Regex::replace`] for more details.)
371
372 ### Example: verbose mode
373
374 When your regex gets complicated, you might consider using something other
375 than regex. But if you stick with regex, you can use the `x` flag to enable
376 insignificant whitespace mode or "verbose mode." In this mode, whitespace
377 is treated as insignificant and one may write comments. This may make your
378 patterns easier to comprehend.
379
380 ```rust
381 use regex::Regex;
382
383 let 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
391 let before = "1973-01-05, 1975-08-25 and 1980-10-18";
392 let after = re.replace_all(before, "$m/$d/$y");
393 assert_eq!(after, "01/05/1973, 08/25/1975 and 10/18/1980");
394 ```
395
396 If 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
398 directly with `\ `, use its hex character code `\x20` or temporarily disable
399 the `x` flag, e.g., `(?-x: )`.
400
401 ### Example: match multiple regular expressions simultaneously
402
403 This demonstrates how to use a [`RegexSet`] to match multiple (possibly
404 overlapping) regexes in a single scan of a haystack:
405
406 ```rust
407 use regex::RegexSet;
408
409 let 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.
421 let matches: Vec<_> = set.matches("foobar").into_iter().collect();
422 assert_eq!(matches, vec![0, 2, 3, 4, 6]);
423
424 // You can also test whether a particular regex matched:
425 let matches = set.matches("foobar");
426 assert!(!matches.matched(5));
427 assert!(matches.matched(6));
428 ```
429
430 # Performance
431
432 This section briefly discusses a few concerns regarding the speed and resource
433 usage of regexes.
434
435 ### Only ask for what you need
436
437 When running a search with a regex, there are generally three different types
438 of information one can ask for:
439
440 1. Does a regex match in a haystack?
441 2. Where does a regex match in a haystack?
442 3. Where do each of the capturing groups match in a haystack?
443
444 Generally speaking, this crate could provide a function to answer only #3,
445 which would subsume #1 and #2 automatically. However, it can be significantly
446 more expensive to compute the location of capturing group matches, so it's best
447 not to do it if you don't need to.
448
449 Therefore, only ask for what you need. For example, don't use [`Regex::find`]
450 if you only need to test if a regex matches a haystack. Use [`Regex::is_match`]
451 instead.
452
453 ### Unicode can impact memory usage and search speed
454
455 This crate has first class support for Unicode and it is **enabled by default**.
456 In many cases, the extra memory required to support it will be negligible and
457 it typically won't impact search speed. But it can in some cases.
458
459 With respect to memory usage, the impact of Unicode principally manifests
460 through the use of Unicode character classes. Unicode character classes
461 tend to be quite large. For example, `\w` by default matches around 140,000
462 distinct codepoints. This requires additional memory, and tends to slow down
463 regex compilation. While a `\w` here and there is unlikely to be noticed,
464 writing `\w{100}` will for example result in quite a large regex by default.
465 Indeed, `\w` is considerably larger than its ASCII-only version, so if your
466 requirements are satisfied by ASCII, it's probably a good idea to stick to
467 ASCII classes. The ASCII-only version of `\w` can be spelled in a number of
468 ways. All of the following are equivalent:
469
470 * `[0-9A-Za-z_]`
471 * `(?-u:\w)`
472 * `[[:word:]]`
473 * `[\w&&\p{ascii}]`
474
475 With respect to search speed, Unicode tends to be handled pretty well, even when
476 using large Unicode character classes. However, some of the faster internal
477 regex engines cannot handle a Unicode aware word boundary assertion. So if you
478 don'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
480 a word character.
481
482 ### Literals might accelerate searches
483
484 This crate tends to be quite good at recognizing literals in a regex pattern
485 and using them to accelerate a search. If it is at all possible to include
486 some kind of literal in your pattern, then it might make search substantially
487 faster. For example, in the regex `\w+@\w+`, the engine will look for
488 occurrences of `@` and then try a reverse match for `\w+` to find the start
489 position.
490
491 ### Avoid re-compiling regexes, especially in a loop
492
493 It is an anti-pattern to compile the same pattern in a loop since regex
494 compilation is typically expensive. (It takes anywhere from a few microseconds
495 to a few **milliseconds** depending on the size of the pattern.) Not only is
496 compilation itself expensive, but this also prevents optimizations that reuse
497 allocations internally to the regex engine.
498
499 In Rust, it can sometimes be a pain to pass regular expressions around if
500 they're used from inside a helper function. Instead, we recommend using
501 [`std::sync::LazyLock`], or the [`once_cell`] crate,
502 if you can't use the standard library.
503
504 This example shows how to use `std::sync::LazyLock`:
505
506 ```rust
507 use std::sync::LazyLock;
508
509 use regex::Regex;
510
511 fn some_helper_function(haystack: &str) -> bool {
512 static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"...").unwrap());
513 RE.is_match(haystack)
514 }
515
516 fn main() {
517 assert!(some_helper_function("abc"));
518 assert!(!some_helper_function("ac"));
519 }
520 ```
521
522 Specifically, in this example, the regex will be compiled when it is used for
523 the first time. On subsequent uses, it will reuse the previously built `Regex`.
524 Notice how one can define the `Regex` locally to a specific function.
525
526 The [`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
533 While a single `Regex` can be freely used from multiple threads simultaneously,
534 there is a small synchronization cost that must be paid. Generally speaking,
535 one shouldn't expect to observe this unless the principal task in each thread
536 is searching with the regex *and* most searches are on short haystacks. In this
537 case, internal contention on shared resources can spike and increase latency,
538 which in turn may slow down each individual search.
539
540 One can work around this by cloning each `Regex` before sending it to another
541 thread. The cloned regexes will still share the same internal read-only portion
542 of its compiled state (it's reference counted), but each thread will get
543 optimized access to the mutable space that is used to run a search. In general,
544 there is no additional cost in memory to doing this. The only cost is the added
545 code 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,
547 but accessing that space is slower.)
548
549 # Unicode
550
551 This section discusses what kind of Unicode support this regex library has.
552 Before showing some examples, we'll summarize the relevant points:
553
554 * This crate almost fully implements "Basic Unicode Support" (Level 1) as
555 specified by the [Unicode Technical Standard #18][UTS18]. The full details
556 of what is supported are documented in [UNICODE.md] in the root of the regex
557 crate 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
560 codepoints in the haystack. That is, the fundamental atom of matching is a
561 single codepoint.
562 * [`bytes::Regex`], in contrast, permits disabling Unicode mode for part of all
563 of your pattern in all cases. When Unicode mode is disabled, then a search is
564 run *as if* iterating over each byte in the haystack. That is, the fundamental
565 atom of matching is a single byte. (A top-level `Regex` also permits disabling
566 Unicode and thus matching *as if* it were one byte at a time, but only when
567 doing so wouldn't permit matching invalid UTF-8.)
568 * When Unicode mode is enabled (the default), `.` will match an entire Unicode
569 scalar value, even when it is encoded using multiple bytes. When Unicode mode
570 is 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.
572 Use `(?-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.
574 To get ASCII-only word boundaries, use `(?-u:\b)` and `(?-u:\B)`. This also
575 applies 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
578 recognize `\n` (assuming CRLF mode is not enabled) and not any of the other
579 forms 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
582 by default via the `\p{property name}` syntax.
583 * In all cases, matches are reported using byte offsets. Or more precisely,
584 UTF-8 code unit offsets. This permits constant time indexing and slicing of the
585 haystack.
586
587 [UTS18]: https://unicode.org/reports/tr18/
588 [UNICODE.md]: https://github.com/rust-lang/regex/blob/master/UNICODE.md
589
590 Patterns themselves are **only** interpreted as a sequence of Unicode scalar
591 values. This means you can use Unicode characters directly in your pattern:
592
593 ```rust
594 use regex::Regex;
595
596 let re = Regex::new(r"(?i)Δ+").unwrap();
597 let m = re.find("ΔδΔ").unwrap();
598 assert_eq!((0, 6), (m.start(), m.end()));
599 // alternatively:
600 assert_eq!(0..6, m.range());
601 ```
602
603 As noted above, Unicode general categories, scripts, script extensions, ages
604 and a smattering of boolean properties are available as character classes. For
605 example, you can match a sequence of numerals, Greek or Cherokee letters:
606
607 ```rust
608 use regex::Regex;
609
610 let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap();
611 let m = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap();
612 assert_eq!(3..23, m.range());
613 ```
614
615 While not specific to Unicode, this library also supports character class set
616 operations. Namely, one can nest character classes arbitrarily and perform set
617 operations on them. Those set operations are union (the default), intersection,
618 difference and symmetric difference. These set operations tend to be most
619 useful with Unicode character classes. For example, to match any codepoint
620 that is both in the `Greek` script and in the `Letter` general category:
621
622 ```rust
623 use regex::Regex;
624
625 let re = Regex::new(r"[\p{Greek}&&\pL]+").unwrap();
626 let subs: Vec<&str> = re.find_iter("ΔδΔ𐅌ΔδΔ").map(|m| m.as_str()).collect();
627 assert_eq!(subs, vec!["ΔδΔ", "ΔδΔ"]);
628
629 // If we just matches on Greek, then all codepoints would match!
630 let re = Regex::new(r"\p{Greek}+").unwrap();
631 let subs: Vec<&str> = re.find_iter("ΔδΔ𐅌ΔδΔ").map(|m| m.as_str()).collect();
632 assert_eq!(subs, vec!["ΔδΔ𐅌ΔδΔ"]);
633 ```
634
635 ### Opt out of Unicode support
636
637 The [`bytes::Regex`] type that can be used to search `&[u8]` haystacks. By
638 default, haystacks are conventionally treated as UTF-8 just like it is with the
639 main `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,
641 when the `u` flag is disabled, `.` will match any byte instead of any Unicode
642 scalar value.
643
644 Disabling the `u` flag is also possible with the standard `&str`-based `Regex`
645 type, but it is only allowed where the UTF-8 invariant is maintained. For
646 example, `(?-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
648 isn't in `(?-u:\w)`, which in turn includes bytes that are invalid UTF-8.
649 Similarly, `(?-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
651 regexes.
652
653 Finally, since Unicode support requires bundling large Unicode data
654 tables, this crate exposes knobs to disable the compilation of those
655 data tables, which can be useful for shrinking binary size and reducing
656 compilation times. For details on how to do that, see the section on [crate
657 features](#crate-features).
658
659 # Syntax
660
661 The syntax supported in this crate is documented below.
662
663 Note that the regular expression parser and abstract syntax are exposed in
664 a 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
696 Any named character class may appear inside a bracketed `[...]` character
697 class. For example, `[\p{Greek}[:digit:]]` matches any ASCII digit or any
698 codepoint in the `Greek` script. `[\p{Greek}&&\pL]` matches Greek letters.
699
700 Precedence in character classes, from most binding to least:
701
702 1. Ranges: `[a-cd]` == `[[a-c]d]`
703 2. Union: `[ab&&bc]` == `[[ab]&&[bc]]`
704 3. Intersection, difference, symmetric difference. All three have equivalent
705 precedence, and are evaluated in left-to-right order. For example,
706 `[\pL--\p{Greek}&&\p{Uppercase}]` == `[[\pL--\p{Greek}]&&\p{Uppercase}]`.
707 4. Negation: `[^a-z&&b]` == `[^[a-z&&b]]`.
708
709 ### Composites
710
711 <pre class="rust">
712 xy concatenation (x followed by y)
713 x|y alternation (x or y, prefer x)
714 </pre>
715
716 This example shows how an alternation works, and what it means to prefer a
717 branch in the alternation over subsequent branches.
718
719 ```
720 use regex::Regex;
721
722 let 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.
726 let re = Regex::new(r"samwise|sam").unwrap();
727 assert_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.
731 let re = Regex::new(r"sam|samwise").unwrap();
732 assert_eq!("sam", re.find(haystack).unwrap().as_str());
733 ```
734
735 ### Repetitions
736
737 <pre class="rust">
738 x* zero or more of x (greedy)
739 x+ one or more of x (greedy)
740 x? zero or one of x (greedy)
741 x*? zero or more of x (ungreedy/lazy)
742 x+? one or more of x (ungreedy/lazy)
743 x?? zero or one of x (ungreedy/lazy)
744 x{n,m} at least n x and at most m x (greedy)
745 x{n,} at least n x (greedy)
746 x{n} exactly n x
747 x{n,m}? at least n x and at most m x (ungreedy/lazy)
748 x{n,}? at least n x (ungreedy/lazy)
749 x{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
767 The empty regex is valid and matches the empty string. For example, the
768 empty regex matches `abc` at positions `0`, `1`, `2` and `3`. When using the
769 top-level [`Regex`] on `&str` haystacks, an empty match that splits a codepoint
770 is guaranteed to never be returned. However, such matches are permitted when
771 using a [`bytes::Regex`]. For example:
772
773 ```rust
774 let re = regex::Regex::new(r"").unwrap();
775 let ranges: Vec<_> = re.find_iter("💩").map(|m| m.range()).collect();
776 assert_eq!(ranges, vec![0..0, 4..4]);
777
778 let re = regex::bytes::Regex::new(r"").unwrap();
779 let ranges: Vec<_> = re.find_iter("💩".as_bytes()).map(|m| m.range()).collect();
780 assert_eq!(ranges, vec![0..0, 1..1, 2..2, 3..3, 4..4]);
781 ```
782
783 Note that an empty regex is distinct from a regex that can never match.
784 For example, the regex `[a&&b]` is a character class that represents the
785 intersection of `a` and `b`. That intersection is empty, which means the
786 character class is empty. Since nothing is in the empty set, `[a&&b]` matches
787 nothing, 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&lt;name&gt;exp) named (also numbered) capture group (names must be alpha-numeric)
794 (?&lt;name&gt;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
800 Capture group names must be any sequence of alpha-numeric Unicode codepoints,
801 in addition to `.`, `_`, `[` and `]`. Names must start with either an `_` or
802 an alphabetic codepoint. Alphabetic codepoints correspond to the `Alphabetic`
803 Unicode property, while numeric codepoints correspond to the union of the
804 `Decimal_Number`, `Letter_Number` and `Other_Number` general categories.
805
806 Flags are each a single character. For example, `(?x)` sets the flag `x`
807 and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
808 the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
809 the `x` flag and clears the `y` flag.
810
811 All flags are by default disabled unless stated otherwise. They are:
812
813 <pre class="rust">
814 i case-insensitive: letters match both upper and lower case
815 m multi-line mode: ^ and $ match begin/end of line
816 s allow . to match \n
817 R enables CRLF mode: when multi-line mode is enabled, \r\n is used
818 U swap the meaning of x* and x*?
819 u Unicode support (enabled by default)
820 x verbose mode, ignores whitespace and allow line comments (starting with `#`)
821 </pre>
822
823 Note that in verbose mode, whitespace is ignored everywhere, including within
824 character classes. To insert whitespace, use its escaped form or a hex literal.
825 For example, `\ ` or `\x20` for an ASCII space.
826
827 Flags can be toggled within a pattern. Here's an example that matches
828 case-insensitively for the first part but case-sensitively for the second part:
829
830 ```rust
831 use regex::Regex;
832
833 let re = Regex::new(r"(?i)a+(?-i)b+").unwrap();
834 let m = re.find("AaAaAbbBBBb").unwrap();
835 assert_eq!(m.as_str(), "AaAaAbb");
836 ```
837
838 Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
839 `b`.
840
841 Multi-line mode means `^` and `$` no longer match just at the beginning/end of
842 the input, but also at the beginning/end of lines:
843
844 ```
845 use regex::Regex;
846
847 let re = Regex::new(r"(?m)^line \d+").unwrap();
848 let m = re.find("line one\nline 2\n").unwrap();
849 assert_eq!(m.as_str(), "line 2");
850 ```
851
852 Note that `^` matches after new lines, even at the end of input:
853
854 ```
855 use regex::Regex;
856
857 let re = Regex::new(r"(?m)^").unwrap();
858 let m = re.find_iter("test\n").last().unwrap();
859 assert_eq!((m.start(), m.end()), (5, 5));
860 ```
861
862 When both CRLF mode and multi-line mode are enabled, then `^` and `$` will
863 match either `\r` or `\n`, but never in the middle of a `\r\n`:
864
865 ```
866 use regex::Regex;
867
868 let re = Regex::new(r"(?mR)^foo$").unwrap();
869 let m = re.find("\r\nfoo\r\n").unwrap();
870 assert_eq!(m.as_str(), "foo");
871 ```
872
873 Unicode 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
875 word boundary instead of a Unicode word boundary, which might make some regex
876 searches run faster:
877
878 ```rust
879 use regex::Regex;
880
881 let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap();
882 let m = re.find("$$abc$$").unwrap();
883 assert_eq!(m.as_str(), "abc");
884 ```
885
886 ### Escape sequences
887
888 Note that this includes all possible escape sequences, even ones that are
889 documented 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
922 These 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
936 These 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
958 This crate is meant to be able to run regex searches on untrusted haystacks
959 without fear of [ReDoS]. This crate also, to a certain extent, supports
960 untrusted patterns.
961
962 [ReDoS]: https://en.wikipedia.org/wiki/ReDoS
963
964 This crate differs from most (but not all) other regex engines in that it
965 doesn't use unbounded backtracking to run a regex search. In those cases,
966 one generally cannot use untrusted patterns *or* untrusted haystacks because
967 it can be very difficult to know whether a particular pattern will result in
968 catastrophic backtracking or not.
969
970 We'll first discuss how this crate deals with untrusted inputs and then wrap
971 it up with a realistic discussion about what practice really looks like.
972
973 ### Panics
974
975 Outside of clearly documented cases, most APIs in this crate are intended to
976 never 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
978 is, it is an API promise that those APIs will never panic no matter what inputs
979 are given to them. With that said, regex engines are complicated beasts, and
980 providing a rock solid guarantee that these APIs literally never panic is
981 essentially equivalent to saying, "there are no bugs in this library." That is
982 a bold claim, and not really one that can be feasibly made with a straight
983 face.
984
985 Don't get the wrong impression here. This crate is extensively tested, not just
986 with unit and integration tests, but also via fuzz testing. For example, this
987 crate is part of the [OSS-fuzz project]. Panics should be incredibly rare, but
988 it is possible for bugs to exist, and thus possible for a panic to occur. If
989 you need a rock solid guarantee against panics, then you should wrap calls into
990 this library with [`std::panic::catch_unwind`].
991
992 It's also worth pointing out that this library will *generally* panic when
993 other regex engines would commit undefined behavior. When undefined behavior
994 occurs, your program might continue as if nothing bad has happened, but it also
995 might mean your program is open to the worst kinds of exploits. In contrast,
996 the 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
1003 The principal way this crate deals with them is by limiting their size by
1004 default. The size limit can be configured via [`RegexBuilder::size_limit`]. The
1005 idea of a size limit is that compiling a pattern into a `Regex` will fail if it
1006 becomes "too big." Namely, while *most* resources consumed by compiling a regex
1007 are approximately proportional (albeit with some high constant factors in some
1008 cases, such as with Unicode character classes) to the length of the pattern
1009 itself, there is one particular exception to this: counted repetitions. Namely,
1010 this pattern:
1011
1012 ```text
1013 a{5}{5}{5}{5}{5}{5}
1014 ```
1015
1016 Is equivalent to this pattern:
1017
1018 ```text
1019 a{15625}
1020 ```
1021
1022 In both of these cases, the actual pattern string is quite small, but the
1023 resulting `Regex` value is quite large. Indeed, as the first pattern shows,
1024 it isn't enough to locally limit the size of each repetition because they can
1025 be stacked in a way that results in exponential growth.
1026
1027 To provide a bit more context, a simplified view of regex compilation looks
1028 like this:
1029
1030 * The pattern string is parsed into a structured representation called an AST.
1031 Counted repetitions are not expanded and Unicode character classes are not
1032 looked up in this stage. That is, the size of the AST is proportional to the
1033 size of the pattern with "reasonable" constant factors. In other words, one
1034 can reasonably limit the memory used by an AST by limiting the length of the
1035 pattern string.
1036 * The AST is translated into an HIR. Counted repetitions are still *not*
1037 expanded at this stage, but Unicode character classes are embedded into the
1038 HIR. The memory usage of a HIR is still proportional to the length of the
1039 original pattern string, but the constant factors---mostly as a result of
1040 Unicode character classes---can be quite high. Still though, the memory used by
1041 an 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
1043 something like `\w{5}` is rewritten to `\w\w\w\w\w`. Thus, this is the stage
1044 at which [`RegexBuilder::size_limit`] is enforced. If the NFA exceeds the
1045 configured size, then this stage will fail.
1046
1047 [Thompson NFA]: https://en.wikipedia.org/wiki/Thompson%27s_construction
1048
1049 The 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
1052 pattern string.
1053 * It avoids long search times. This will be discussed in more detail in the
1054 next section, but worst case search time *is* dependent on the size of the
1055 regex. So keeping regexes limited to a reasonable size is also a way of keeping
1056 search times reasonable.
1057
1058 Finally, it's worth pointing out that regex compilation is guaranteed to take
1059 worst case `O(m)` time, where `m` is proportional to the size of regex. The
1060 size 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
1063 something small and expand it as needed. Configure [`RegexBuilder::size_limit`]
1064 to something small and then expand it as needed.
1065
1066 ### Untrusted haystacks
1067
1068 The main way this crate guards against searches from taking a long time is by
1069 using algorithms that guarantee a `O(m * n)` worst case time and space bound.
1070 Namely:
1071
1072 * `m` is proportional to the size of the regex, where the size of the regex
1073 includes the expansion of all counted repetitions. (See the previous section on
1074 untrusted patterns.)
1075 * `n` is proportional to the length, in bytes, of the haystack.
1076
1077 In other words, if you consider `m` to be a constant (for example, the regex
1078 pattern is a literal in the source code), then the search can be said to run
1079 in "linear time." Or equivalently, "linear time with respect to the size of the
1080 haystack."
1081
1082 But the `m` factor here is important not to ignore. If a regex is
1083 particularly 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
1087 are not enormous, you should expect to be able to search untrusted haystacks
1088 without fear. If you aren't sure, you should benchmark it. Unlike backtracking
1089 engines, if your regex is so big that it's likely to result in slow searches,
1090 this is probably something you'll be able to observe regardless of what the
1091 haystack is made up of.
1092
1093 ### Iterating over matches
1094
1095 One thing that is perhaps easy to miss is that the worst case time
1096 complexity 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
1099 all matches can execute many searches, and each search can scan the entire
1100 haystack, the worst case time complexity for iterators is `O(m * n^2)`.
1101
1102 One example of where this occurs is when a pattern consists of an alternation,
1103 where an earlier branch of the alternation requires scanning the entire
1104 haystack only to discover that there is no match. It also requires a later
1105 branch of the alternation to have matched at the beginning of the search. For
1106 example, consider the pattern `.*[^A-Z]|[A-Z]` and the haystack `AAAAA`. The
1107 first search will scan to the end looking for matches of `.*[^A-Z]` even though
1108 a finite automata engine (as in this crate) knows that `[A-Z]` has already
1109 matched the first character of the haystack. This is due to the greedy nature
1110 of regex searching. That first search will report a match at the first `A` only
1111 after scanning to the end to discover that no other match exists. The next
1112 search then begins at the second `A` and the behavior repeats.
1113
1114 There is no way to avoid this. This means that if both patterns and haystacks
1115 are untrusted and you're iterating over all matches, you're susceptible to
1116 worst case quadratic time complexity. One possible way to mitigate this
1117 is 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
1119 in "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
1121 the normal greedy match semantics of regex searches and instead ask the regex
1122 engine to immediately stop as soon as a match has been found. Enabling this
1123 mode will thus restore the worst case `O(m * n)` time complexity bound, but at
1124 the cost of different semantics.
1125
1126 ### Untrusted inputs in practice
1127
1128 While providing a `O(m * n)` worst case time bound on all searches goes a long
1129 way toward preventing [ReDoS], that doesn't mean every search you can possibly
1130 run will complete without burning CPU time. In general, there are a few ways
1131 for the `m * n` time bound to still bite you:
1132
1133 * You are searching an exceptionally long haystack. No matter how you slice
1134 it, a longer haystack will take more time to search. This crate may often make
1135 very quick work of even long haystacks because of its literal optimizations,
1136 but those aren't available for all regexes.
1137 * Unicode character classes can cause searches to be quite slow in some cases.
1138 This is especially true when they are combined with counted repetitions. While
1139 the regex size limit above will protect you from the most egregious cases,
1140 the default size limit still permits pretty big regexes that can execute more
1141 slowly than one might expect.
1142 * While routines like [`Regex::find`] and [`Regex::captures`] guarantee
1143 worst 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.
1145 This is because `find_iter` runs many searches, and each search takes worst
1146 case `O(m * n)` time. Thus, iteration of all matches in a haystack has
1147 worst 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
1150 In general, untrusted haystacks are easier to stomach than untrusted patterns.
1151 Untrusted patterns give a lot more control to the caller to impact the
1152 performance of a search. In many cases, a regex search will actually execute in
1153 average case `O(n)` time (i.e., not dependent on the size of the regex), but
1154 this can't be guaranteed in general. Therefore, permitting untrusted patterns
1155 means that your only line of defense is to put a limit on how big `m` (and
1156 perhaps also `n`) can be in `O(m * n)`. `n` is limited by simply inspecting
1157 the length of the haystack while `m` is limited by *both* applying a limit to
1158 the length of the pattern *and* a limit on the compiled size of the regex via
1159 [`RegexBuilder::size_limit`].
1160
1161 It bears repeating: if you're accepting untrusted patterns, it would be a good
1162 idea to start with conservative limits on `m` and `n`, and then carefully
1163 increase them as needed.
1164
1165 # Crate features
1166
1167 By default, this crate tries pretty hard to make regex matching both as fast
1168 as possible and as correct as it can be. This means that there is a lot of
1169 code dedicated to performance, the handling of Unicode data and the Unicode
1170 data itself. Overall, this leads to more dependencies, larger binaries and
1171 longer compile times. This trade off may not be appropriate in all cases, and
1172 indeed, even when all Unicode and performance features are disabled, one is
1173 still left with a perfectly serviceable regex engine that will work well in
1174 many cases. (Note that code is not arbitrarily reducible, and for this reason,
1175 the [`regex-lite`](https://docs.rs/regex-lite) crate exists to provide an even
1176 more minimal experience by cutting out Unicode and performance, but still
1177 maintaining the linear search time bound.)
1178
1179 This crate exposes a number of features for controlling that trade off. Some
1180 of these features are strictly performance oriented, such that disabling them
1181 won't result in a loss of functionality, but may result in worse performance.
1182 Other features, such as the ones controlling the presence or absence of Unicode
1183 data, 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`
1185 will fail since Unicode case insensitivity is enabled by default. Instead,
1186 callers must use `(?i-u)a` to disable Unicode case folding. Stated differently,
1187 enabling or disabling any of the features below can only add or subtract from
1188 the total set of valid regular expressions. Enabling or disabling a feature
1189 will never modify the match semantics of a regular expression.
1190
1191 Most features below are enabled by default. Features that aren't enabled by
1192 default 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
1300 This crate has two required dependencies and several optional dependencies.
1301 This section briefly describes them with the goal of raising awareness of how
1302 different components of this crate may be used independently.
1303
1304 It is somewhat unusual for a regex engine to have dependencies, as most regex
1305 libraries are self contained units with no dependencies other than a particular
1306 environment's standard library. Indeed, for other similarly optimized regex
1307 engines, most or all of the code in the dependencies of this crate would
1308 normally just be inseparable or coupled parts of the crate itself. But since
1309 Rust and its tooling ecosystem make the use of dependencies so easy, it made
1310 sense to spend some effort de-coupling parts of this crate and making them
1311 independently useful.
1312
1313 We only briefly describe each crate here.
1314
1315 * [`regex-lite`](https://docs.rs/regex-lite) is not a dependency of `regex`,
1316 but rather, a standalone zero-dependency simpler version of `regex` that
1317 prioritizes compile times and binary size. In exchange, it eschews Unicode
1318 support and performance. Its match semantics are as identical as possible to
1319 the `regex` crate, and for the things it supports, its APIs are identical to
1320 the APIs in this crate. In other words, for a lot of use cases, it is a drop-in
1321 replacement.
1322 * [`regex-syntax`](https://docs.rs/regex-syntax) provides a regular expression
1323 parser via `Ast` and `Hir` types. It also provides routines for extracting
1324 literals from a pattern. Folks can use this crate to do analysis, or even to
1325 build their own regex engine without having to worry about writing a parser.
1326 * [`regex-automata`](https://docs.rs/regex-automata) provides the regex engines
1327 themselves. One of the downsides of finite automata based regex engines is that
1328 they often need multiple internal engines in order to have similar or better
1329 performance than an unbounded backtracking engine in practice. `regex-automata`
1330 in particular provides public APIs for a PikeVM, a bounded backtracker, a
1331 one-pass DFA, a lazy DFA, a fully compiled DFA and a meta regex engine that
1332 combines all them together. It also has native multi-pattern support and
1333 provides a way to compile and serialize full DFAs such that they can be loaded
1334 and searched in a no-std no-alloc environment. `regex-automata` itself doesn't
1335 even have a required dependency on `regex-syntax`!
1336 * [`memchr`](https://docs.rs/memchr) provides low level SIMD vectorized
1337 routines for quickly finding the location of single bytes or even substrings
1338 in a haystack. In other words, it provides fast `memchr` and `memmem` routines.
1339 These are used by this crate in literal optimizations.
1340 * [`aho-corasick`](https://docs.rs/aho-corasick) provides multi-substring
1341 search. It also provides SIMD vectorized routines in the case where the number
1342 of substrings to search for is relatively small. The `regex` crate also uses
1343 this 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)]
1355 doc_comment::doctest!("../README.md");
1356
1357 extern crate alloc;
1358 #[cfg(any(test, feature = "std"))]
1359 extern crate std;
1360
1361 pub use crate::error::Error;
1362
1363 pub use crate::{builders::string::*, regex::string::*, regexset::string::*};
1364
1365 mod builders;
1366 pub mod bytes;
1367 mod error;
1368 mod find_byte;
1369 #[cfg(feature = "pattern")]
1370 mod pattern;
1371 mod regex;
1372 mod 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.
1378 pub 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)]
1384 pub mod __private {
1385 pub use regex_automata::util::lazy::Lazy;
1386 }