1/*!
2This crate provides a library for parsing, compiling, and executing regular
3expressions. Its syntax is similar to Perl-style regular expressions, but lacks
4a few features like look around and backreferences. In exchange, all searches
5execute in linear time with respect to the size of the regular expression and
6search text.
7
8This crate's documentation provides some simple examples, describes
9[Unicode support](#unicode) and exhaustively lists the
10[supported syntax](#syntax).
11
12For more specific details on the API for regular expressions, please see the
13documentation for the [`Regex`](struct.Regex.html) type.
14
15# Usage
16
17This crate is [on crates.io](https://crates.io/crates/regex) and can be
18used by adding `regex` to your dependencies in your project's `Cargo.toml`.
19
20```toml
21[dependencies]
22regex = "1"
23```
24
25# Example: find a date
26
27General use of regular expressions in this package involves compiling an
28expression and then using it to search, split or replace text. For example,
29to confirm that some text resembles a date:
30
31```rust
32use regex::Regex;
33let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
34assert!(re.is_match("2014-01-01"));
35```
36
37Notice the use of the `^` and `$` anchors. In this crate, every expression
38is executed with an implicit `.*?` at the beginning and end, which allows
39it to match anywhere in the text. Anchors can be used to ensure that the
40full text matches an expression.
41
42This example also demonstrates the utility of
43[raw strings](https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals)
44in Rust, which
45are just like regular strings except they are prefixed with an `r` and do
46not process any escape sequences. For example, `"\\d"` is the same
47expression as `r"\d"`.
48
49# Example: Avoid compiling the same regex in a loop
50
51It is an anti-pattern to compile the same regular expression in a loop
52since compilation is typically expensive. (It takes anywhere from a few
53microseconds to a few **milliseconds** depending on the size of the
54regex.) Not only is compilation itself expensive, but this also prevents
55optimizations that reuse allocations internally to the matching engines.
56
57In Rust, it can sometimes be a pain to pass regular expressions around if
58they're used from inside a helper function. Instead, we recommend using the
59[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that
60regular expressions are compiled exactly once.
61
62For example:
63
64```rust
65use lazy_static::lazy_static;
66use regex::Regex;
67
68fn some_helper_function(text: &str) -> bool {
69 lazy_static! {
70 static ref RE: Regex = Regex::new("...").unwrap();
71 }
72 RE.is_match(text)
73}
74
75fn main() {}
76```
77
78Specifically, in this example, the regex will be compiled when it is used for
79the first time. On subsequent uses, it will reuse the previous compilation.
80
81# Example: iterating over capture groups
82
83This crate provides convenient iterators for matching an expression
84repeatedly against a search string to find successive non-overlapping
85matches. For example, to find all dates in a string and be able to access
86them by their component pieces:
87
88```rust
89# use regex::Regex;
90# fn main() {
91let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
92let text = "2012-03-14, 2013-01-01 and 2014-07-05";
93for cap in re.captures_iter(text) {
94 println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]);
95}
96// Output:
97// Month: 03 Day: 14 Year: 2012
98// Month: 01 Day: 01 Year: 2013
99// Month: 07 Day: 05 Year: 2014
100# }
101```
102
103Notice that the year is in the capture group indexed at `1`. This is
104because the *entire match* is stored in the capture group at index `0`.
105
106# Example: replacement with named capture groups
107
108Building on the previous example, perhaps we'd like to rearrange the date
109formats. This can be done with text replacement. But to make the code
110clearer, we can *name* our capture groups and use those names as variables
111in our replacement text:
112
113```rust
114# use regex::Regex;
115# fn main() {
116let re = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})").unwrap();
117let before = "2012-03-14, 2013-01-01 and 2014-07-05";
118let after = re.replace_all(before, "$m/$d/$y");
119assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014");
120# }
121```
122
123The `replace` methods are actually polymorphic in the replacement, which
124provides more flexibility than is seen here. (See the documentation for
125`Regex::replace` for more details.)
126
127Note that if your regex gets complicated, you can use the `x` flag to
128enable insignificant whitespace mode, which also lets you write comments:
129
130```rust
131# use regex::Regex;
132# fn main() {
133let re = Regex::new(r"(?x)
134 (?P<y>\d{4}) # the year
135 -
136 (?P<m>\d{2}) # the month
137 -
138 (?P<d>\d{2}) # the day
139").unwrap();
140let before = "2012-03-14, 2013-01-01 and 2014-07-05";
141let after = re.replace_all(before, "$m/$d/$y");
142assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014");
143# }
144```
145
146If you wish to match against whitespace in this mode, you can still use `\s`,
147`\n`, `\t`, etc. For escaping a single space character, you can escape it
148directly with `\ `, use its hex character code `\x20` or temporarily disable
149the `x` flag, e.g., `(?-x: )`.
150
151# Example: match multiple regular expressions simultaneously
152
153This demonstrates how to use a `RegexSet` to match multiple (possibly
154overlapping) regular expressions in a single scan of the search text:
155
156```rust
157use regex::RegexSet;
158
159let set = RegexSet::new(&[
160 r"\w+",
161 r"\d+",
162 r"\pL+",
163 r"foo",
164 r"bar",
165 r"barfoo",
166 r"foobar",
167]).unwrap();
168
169// Iterate over and collect all of the matches.
170let matches: Vec<_> = set.matches("foobar").into_iter().collect();
171assert_eq!(matches, vec![0, 2, 3, 4, 6]);
172
173// You can also test whether a particular regex matched:
174let matches = set.matches("foobar");
175assert!(!matches.matched(5));
176assert!(matches.matched(6));
177```
178
179# Pay for what you use
180
181With respect to searching text with a regular expression, there are three
182questions that can be asked:
183
1841. Does the text match this expression?
1852. If so, where does it match?
1863. Where did the capturing groups match?
187
188Generally speaking, this crate could provide a function to answer only #3,
189which would subsume #1 and #2 automatically. However, it can be significantly
190more expensive to compute the location of capturing group matches, so it's best
191not to do it if you don't need to.
192
193Therefore, only use what you need. For example, don't use `find` if you
194only need to test if an expression matches a string. (Use `is_match`
195instead.)
196
197# Unicode
198
199This implementation executes regular expressions **only** on valid UTF-8
200while exposing match locations as byte indices into the search string. (To
201relax this restriction, use the [`bytes`](bytes/index.html) sub-module.)
202Conceptually, the regex engine works by matching a haystack as if it were a
203sequence of Unicode scalar values.
204
205Only simple case folding is supported. Namely, when matching
206case-insensitively, the characters are first mapped using the "simple" case
207folding rules defined by Unicode.
208
209Regular expressions themselves are **only** interpreted as a sequence of
210Unicode scalar values. This means you can use Unicode characters directly
211in your expression:
212
213```rust
214# use regex::Regex;
215# fn main() {
216let re = Regex::new(r"(?i)Δ+").unwrap();
217let mat = re.find("ΔδΔ").unwrap();
218assert_eq!((mat.start(), mat.end()), (0, 6));
219# }
220```
221
222Most features of the regular expressions in this crate are Unicode aware. Here
223are some examples:
224
225* `.` will match any valid UTF-8 encoded Unicode scalar value except for `\n`.
226 (To also match `\n`, enable the `s` flag, e.g., `(?s:.)`.)
227* `\w`, `\d` and `\s` are Unicode aware. For example, `\s` will match all forms
228 of whitespace categorized by Unicode.
229* `\b` matches a Unicode word boundary.
230* Negated character classes like `[^a]` match all Unicode scalar values except
231 for `a`.
232* `^` and `$` are **not** Unicode aware in multi-line mode. Namely, they only
233 recognize `\n` and not any of the other forms of line terminators defined
234 by Unicode.
235
236Unicode general categories, scripts, script extensions, ages and a smattering
237of boolean properties are available as character classes. For example, you can
238match a sequence of numerals, Greek or Cherokee letters:
239
240```rust
241# use regex::Regex;
242# fn main() {
243let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap();
244let mat = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap();
245assert_eq!((mat.start(), mat.end()), (3, 23));
246# }
247```
248
249For a more detailed breakdown of Unicode support with respect to
250[UTS#18](https://unicode.org/reports/tr18/),
251please see the
252[UNICODE](https://github.com/rust-lang/regex/blob/master/UNICODE.md)
253document in the root of the regex repository.
254
255# Opt out of Unicode support
256
257The `bytes` sub-module provides a `Regex` type that can be used to match
258on `&[u8]`. By default, text is interpreted as UTF-8 just like it is with
259the main `Regex` type. However, this behavior can be disabled by turning
260off the `u` flag, even if doing so could result in matching invalid UTF-8.
261For example, when the `u` flag is disabled, `.` will match any byte instead
262of any Unicode scalar value.
263
264Disabling the `u` flag is also possible with the standard `&str`-based `Regex`
265type, but it is only allowed where the UTF-8 invariant is maintained. For
266example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an
267`&str`-based `Regex`, but `(?-u:\xFF)` will attempt to match the raw byte
268`\xFF`, which is invalid UTF-8 and therefore is illegal in `&str`-based
269regexes.
270
271Finally, since Unicode support requires bundling large Unicode data
272tables, this crate exposes knobs to disable the compilation of those
273data tables, which can be useful for shrinking binary size and reducing
274compilation times. For details on how to do that, see the section on [crate
275features](#crate-features).
276
277# Syntax
278
279The syntax supported in this crate is documented below.
280
281Note that the regular expression parser and abstract syntax are exposed in
282a separate crate, [`regex-syntax`](https://docs.rs/regex-syntax).
283
284## Matching one character
285
286<pre class="rust">
287. any character except new line (includes new line with s flag)
288\d digit (\p{Nd})
289\D not digit
290\pX Unicode character class identified by a one-letter name
291\p{Greek} Unicode character class (general category or script)
292\PX Negated Unicode character class identified by a one-letter name
293\P{Greek} negated Unicode character class (general category or script)
294</pre>
295
296### Character classes
297
298<pre class="rust">
299[xyz] A character class matching either x, y or z (union).
300[^xyz] A character class matching any character except x, y and z.
301[a-z] A character class matching any character in range a-z.
302[[:alpha:]] ASCII character class ([A-Za-z])
303[[:^alpha:]] Negated ASCII character class ([^A-Za-z])
304[x[^xyz]] Nested/grouping character class (matching any character except y and z)
305[a-y&&xyz] Intersection (matching x or y)
306[0-9&&[^4]] Subtraction using intersection and negation (matching 0-9 except 4)
307[0-9--4] Direct subtraction (matching 0-9 except 4)
308[a-g~~b-h] Symmetric difference (matching `a` and `h` only)
309[\[\]] Escaping in character classes (matching [ or ])
310</pre>
311
312Any named character class may appear inside a bracketed `[...]` character
313class. For example, `[\p{Greek}[:digit:]]` matches any Greek or ASCII
314digit. `[\p{Greek}&&\pL]` matches Greek letters.
315
316Precedence in character classes, from most binding to least:
317
3181. Ranges: `a-cd` == `[a-c]d`
3192. Union: `ab&&bc` == `[ab]&&[bc]`
3203. Intersection: `^a-z&&b` == `^[a-z&&b]`
3214. Negation
322
323## Composites
324
325<pre class="rust">
326xy concatenation (x followed by y)
327x|y alternation (x or y, prefer x)
328</pre>
329
330This example shows how an alternation works, and what it means to prefer a
331branch in the alternation over subsequent branches.
332
333```
334use regex::Regex;
335
336let haystack = "samwise";
337// If 'samwise' comes first in our alternation, then it is
338// preferred as a match, even if the regex engine could
339// technically detect that 'sam' led to a match earlier.
340let re = Regex::new(r"samwise|sam").unwrap();
341assert_eq!("samwise", re.find(haystack).unwrap().as_str());
342// But if 'sam' comes first, then it will match instead.
343// In this case, it is impossible for 'samwise' to match
344// because 'sam' is a prefix of it.
345let re = Regex::new(r"sam|samwise").unwrap();
346assert_eq!("sam", re.find(haystack).unwrap().as_str());
347```
348
349## Repetitions
350
351<pre class="rust">
352x* zero or more of x (greedy)
353x+ one or more of x (greedy)
354x? zero or one of x (greedy)
355x*? zero or more of x (ungreedy/lazy)
356x+? one or more of x (ungreedy/lazy)
357x?? zero or one of x (ungreedy/lazy)
358x{n,m} at least n x and at most m x (greedy)
359x{n,} at least n x (greedy)
360x{n} exactly n x
361x{n,m}? at least n x and at most m x (ungreedy/lazy)
362x{n,}? at least n x (ungreedy/lazy)
363x{n}? exactly n x
364</pre>
365
366## Empty matches
367
368<pre class="rust">
369^ the beginning of text (or start-of-line with multi-line mode)
370$ the end of text (or end-of-line with multi-line mode)
371\A only the beginning of text (even with multi-line mode enabled)
372\z only the end of text (even with multi-line mode enabled)
373\b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
374\B not a Unicode word boundary
375</pre>
376
377The empty regex is valid and matches the empty string. For example, the empty
378regex matches `abc` at positions `0`, `1`, `2` and `3`.
379
380## Grouping and flags
381
382<pre class="rust">
383(exp) numbered capture group (indexed by opening parenthesis)
384(?P&lt;name&gt;exp) named (also numbered) capture group (names must be alpha-numeric)
385(?&lt;name&gt;exp) named (also numbered) capture group (names must be alpha-numeric)
386(?:exp) non-capturing group
387(?flags) set flags within current group
388(?flags:exp) set flags for exp (non-capturing)
389</pre>
390
391Capture group names must be any sequence of alpha-numeric Unicode codepoints,
392in addition to `.`, `_`, `[` and `]`. Names must start with either an `_` or
393an alphabetic codepoint. Alphabetic codepoints correspond to the `Alphabetic`
394Unicode property, while numeric codepoints correspond to the union of the
395`Decimal_Number`, `Letter_Number` and `Other_Number` general categories.
396
397Flags are each a single character. For example, `(?x)` sets the flag `x`
398and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
399the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
400the `x` flag and clears the `y` flag.
401
402All flags are by default disabled unless stated otherwise. They are:
403
404<pre class="rust">
405i case-insensitive: letters match both upper and lower case
406m multi-line mode: ^ and $ match begin/end of line
407s allow . to match \n
408U swap the meaning of x* and x*?
409u Unicode support (enabled by default)
410x verbose mode, ignores whitespace and allow line comments (starting with `#`)
411</pre>
412
413Note that in verbose mode, whitespace is ignored everywhere, including within
414character classes. To insert whitespace, use its escaped form or a hex literal.
415For example, `\ ` or `\x20` for an ASCII space.
416
417Flags can be toggled within a pattern. Here's an example that matches
418case-insensitively for the first part but case-sensitively for the second part:
419
420```rust
421# use regex::Regex;
422# fn main() {
423let re = Regex::new(r"(?i)a+(?-i)b+").unwrap();
424let cap = re.captures("AaAaAbbBBBb").unwrap();
425assert_eq!(&cap[0], "AaAaAbb");
426# }
427```
428
429Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
430`b`.
431
432Multi-line mode means `^` and `$` no longer match just at the beginning/end of
433the input, but at the beginning/end of lines:
434
435```
436# use regex::Regex;
437let re = Regex::new(r"(?m)^line \d+").unwrap();
438let m = re.find("line one\nline 2\n").unwrap();
439assert_eq!(m.as_str(), "line 2");
440```
441
442Note that `^` matches after new lines, even at the end of input:
443
444```
445# use regex::Regex;
446let re = Regex::new(r"(?m)^").unwrap();
447let m = re.find_iter("test\n").last().unwrap();
448assert_eq!((m.start(), m.end()), (5, 5));
449```
450
451Here is an example that uses an ASCII word boundary instead of a Unicode
452word boundary:
453
454```rust
455# use regex::Regex;
456# fn main() {
457let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap();
458let cap = re.captures("$$abc$$").unwrap();
459assert_eq!(&cap[0], "abc");
460# }
461```
462
463## Escape sequences
464
465<pre class="rust">
466\* literal *, works for any punctuation character: \.+*?()|[]{}^$
467\a bell (\x07)
468\f form feed (\x0C)
469\t horizontal tab
470\n new line
471\r carriage return
472\v vertical tab (\x0B)
473\123 octal character code (up to three digits) (when enabled)
474\x7F hex character code (exactly two digits)
475\x{10FFFF} any hex character code corresponding to a Unicode code point
476\u007F hex character code (exactly four digits)
477\u{7F} any hex character code corresponding to a Unicode code point
478\U0000007F hex character code (exactly eight digits)
479\U{7F} any hex character code corresponding to a Unicode code point
480</pre>
481
482## Perl character classes (Unicode friendly)
483
484These classes are based on the definitions provided in
485[UTS#18](https://www.unicode.org/reports/tr18/#Compatibility_Properties):
486
487<pre class="rust">
488\d digit (\p{Nd})
489\D not digit
490\s whitespace (\p{White_Space})
491\S not whitespace
492\w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
493\W not word character
494</pre>
495
496## ASCII character classes
497
498<pre class="rust">
499[[:alnum:]] alphanumeric ([0-9A-Za-z])
500[[:alpha:]] alphabetic ([A-Za-z])
501[[:ascii:]] ASCII ([\x00-\x7F])
502[[:blank:]] blank ([\t ])
503[[:cntrl:]] control ([\x00-\x1F\x7F])
504[[:digit:]] digits ([0-9])
505[[:graph:]] graphical ([!-~])
506[[:lower:]] lower case ([a-z])
507[[:print:]] printable ([ -~])
508[[:punct:]] punctuation ([!-/:-@\[-`{-~])
509[[:space:]] whitespace ([\t\n\v\f\r ])
510[[:upper:]] upper case ([A-Z])
511[[:word:]] word characters ([0-9A-Za-z_])
512[[:xdigit:]] hex digit ([0-9A-Fa-f])
513</pre>
514
515# Crate features
516
517By default, this crate tries pretty hard to make regex matching both as fast
518as possible and as correct as it can be, within reason. This means that there
519is a lot of code dedicated to performance, the handling of Unicode data and the
520Unicode data itself. Overall, this leads to more dependencies, larger binaries
521and longer compile times. This trade off may not be appropriate in all cases,
522and indeed, even when all Unicode and performance features are disabled, one
523is still left with a perfectly serviceable regex engine that will work well
524in many cases.
525
526This crate exposes a number of features for controlling that trade off. Some
527of these features are strictly performance oriented, such that disabling them
528won't result in a loss of functionality, but may result in worse performance.
529Other features, such as the ones controlling the presence or absence of Unicode
530data, can result in a loss of functionality. For example, if one disables the
531`unicode-case` feature (described below), then compiling the regex `(?i)a`
532will fail since Unicode case insensitivity is enabled by default. Instead,
533callers must use `(?i-u)a` instead to disable Unicode case folding. Stated
534differently, enabling or disabling any of the features below can only add or
535subtract from the total set of valid regular expressions. Enabling or disabling
536a feature will never modify the match semantics of a regular expression.
537
538All features below are enabled by default.
539
540### Ecosystem features
541
542* **std** -
543 When enabled, this will cause `regex` to use the standard library. Currently,
544 disabling this feature will always result in a compilation error. It is
545 intended to add `alloc`-only support to regex in the future.
546
547### Performance features
548
549* **perf** -
550 Enables all performance related features. This feature is enabled by default
551 and will always cover all features that improve performance, even if more
552 are added in the future.
553* **perf-dfa** -
554 Enables the use of a lazy DFA for matching. The lazy DFA is used to compile
555 portions of a regex to a very fast DFA on an as-needed basis. This can
556 result in substantial speedups, usually by an order of magnitude on large
557 haystacks. The lazy DFA does not bring in any new dependencies, but it can
558 make compile times longer.
559* **perf-inline** -
560 Enables the use of aggressive inlining inside match routines. This reduces
561 the overhead of each match. The aggressive inlining, however, increases
562 compile times and binary size.
563* **perf-literal** -
564 Enables the use of literal optimizations for speeding up matches. In some
565 cases, literal optimizations can result in speedups of _several_ orders of
566 magnitude. Disabling this drops the `aho-corasick` and `memchr` dependencies.
567* **perf-cache** -
568 This feature used to enable a faster internal cache at the cost of using
569 additional dependencies, but this is no longer an option. A fast internal
570 cache is now used unconditionally with no additional dependencies. This may
571 change in the future.
572
573### Unicode features
574
575* **unicode** -
576 Enables all Unicode features. This feature is enabled by default, and will
577 always cover all Unicode features, even if more are added in the future.
578* **unicode-age** -
579 Provide the data for the
580 [Unicode `Age` property](https://www.unicode.org/reports/tr44/tr44-24.html#Character_Age).
581 This makes it possible to use classes like `\p{Age:6.0}` to refer to all
582 codepoints first introduced in Unicode 6.0
583* **unicode-bool** -
584 Provide the data for numerous Unicode boolean properties. The full list
585 is not included here, but contains properties like `Alphabetic`, `Emoji`,
586 `Lowercase`, `Math`, `Uppercase` and `White_Space`.
587* **unicode-case** -
588 Provide the data for case insensitive matching using
589 [Unicode's "simple loose matches" specification](https://www.unicode.org/reports/tr18/#Simple_Loose_Matches).
590* **unicode-gencat** -
591 Provide the data for
592 [Unicode general categories](https://www.unicode.org/reports/tr44/tr44-24.html#General_Category_Values).
593 This includes, but is not limited to, `Decimal_Number`, `Letter`,
594 `Math_Symbol`, `Number` and `Punctuation`.
595* **unicode-perl** -
596 Provide the data for supporting the Unicode-aware Perl character classes,
597 corresponding to `\w`, `\s` and `\d`. This is also necessary for using
598 Unicode-aware word boundary assertions. Note that if this feature is
599 disabled, the `\s` and `\d` character classes are still available if the
600 `unicode-bool` and `unicode-gencat` features are enabled, respectively.
601* **unicode-script** -
602 Provide the data for
603 [Unicode scripts and script extensions](https://www.unicode.org/reports/tr24/).
604 This includes, but is not limited to, `Arabic`, `Cyrillic`, `Hebrew`,
605 `Latin` and `Thai`.
606* **unicode-segment** -
607 Provide the data necessary to provide the properties used to implement the
608 [Unicode text segmentation algorithms](https://www.unicode.org/reports/tr29/).
609 This enables using classes like `\p{gcb=Extend}`, `\p{wb=Katakana}` and
610 `\p{sb=ATerm}`.
611
612
613# Untrusted input
614
615This crate can handle both untrusted regular expressions and untrusted
616search text.
617
618Untrusted regular expressions are handled by capping the size of a compiled
619regular expression.
620(See [`RegexBuilder::size_limit`](struct.RegexBuilder.html#method.size_limit).)
621Without this, it would be trivial for an attacker to exhaust your system's
622memory with expressions like `a{100}{100}{100}`.
623
624Untrusted search text is allowed because the matching engine(s) in this
625crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search
626text`), which means there's no way to cause exponential blow-up like with
627some other regular expression engines. (We pay for this by disallowing
628features like arbitrary look-ahead and backreferences.)
629
630When a DFA is used, pathological cases with exponential state blow-up are
631avoided by constructing the DFA lazily or in an "online" manner. Therefore,
632at most one new state can be created for each byte of input. This satisfies
633our time complexity guarantees, but can lead to memory growth
634proportional to the size of the input. As a stopgap, the DFA is only
635allowed to store a fixed number of states. When the limit is reached, its
636states are wiped and continues on, possibly duplicating previous work. If
637the limit is reached too frequently, it gives up and hands control off to
638another matching engine with fixed memory requirements.
639(The DFA size limit can also be tweaked. See
640[`RegexBuilder::dfa_size_limit`](struct.RegexBuilder.html#method.dfa_size_limit).)
641*/
642
643#![deny(missing_docs)]
644#![cfg_attr(feature = "pattern", feature(pattern))]
645#![warn(missing_debug_implementations)]
646
647#[cfg(not(feature = "std"))]
648compile_error!("`std` feature is currently required to build this crate");
649
650// To check README's example
651// TODO: Re-enable this once the MSRV is 1.43 or greater.
652// See: https://github.com/rust-lang/regex/issues/684
653// See: https://github.com/rust-lang/regex/issues/685
654// #[cfg(doctest)]
655// doc_comment::doctest!("../README.md");
656
657#[cfg(feature = "std")]
658pub use crate::error::Error;
659#[cfg(feature = "std")]
660pub use crate::re_builder::set_unicode::*;
661#[cfg(feature = "std")]
662pub use crate::re_builder::unicode::*;
663#[cfg(feature = "std")]
664pub use crate::re_set::unicode::*;
665#[cfg(feature = "std")]
666pub use crate::re_unicode::{
667 escape, CaptureLocations, CaptureMatches, CaptureNames, Captures,
668 Locations, Match, Matches, NoExpand, Regex, Replacer, ReplacerRef, Split,
669 SplitN, SubCaptureMatches,
670};
671
672/**
673Match regular expressions on arbitrary bytes.
674
675This module provides a nearly identical API to the one found in the
676top-level of this crate. There are two important differences:
677
6781. Matching is done on `&[u8]` instead of `&str`. Additionally, `Vec<u8>`
679is used where `String` would have been used.
6802. Unicode support can be disabled even when disabling it would result in
681matching invalid UTF-8 bytes.
682
683# Example: match null terminated string
684
685This shows how to find all null-terminated strings in a slice of bytes:
686
687```rust
688# use regex::bytes::Regex;
689let re = Regex::new(r"(?-u)(?P<cstr>[^\x00]+)\x00").unwrap();
690let text = b"foo\x00bar\x00baz\x00";
691
692// Extract all of the strings without the null terminator from each match.
693// The unwrap is OK here since a match requires the `cstr` capture to match.
694let cstrs: Vec<&[u8]> =
695 re.captures_iter(text)
696 .map(|c| c.name("cstr").unwrap().as_bytes())
697 .collect();
698assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs);
699```
700
701# Example: selectively enable Unicode support
702
703This shows how to match an arbitrary byte pattern followed by a UTF-8 encoded
704string (e.g., to extract a title from a Matroska file):
705
706```rust
707# use std::str;
708# use regex::bytes::Regex;
709let re = Regex::new(
710 r"(?-u)\x7b\xa9(?:[\x80-\xfe]|[\x40-\xff].)(?u:(.*))"
711).unwrap();
712let text = b"\x12\xd0\x3b\x5f\x7b\xa9\x85\xe2\x98\x83\x80\x98\x54\x76\x68\x65";
713let caps = re.captures(text).unwrap();
714
715// Notice that despite the `.*` at the end, it will only match valid UTF-8
716// because Unicode mode was enabled with the `u` flag. Without the `u` flag,
717// the `.*` would match the rest of the bytes.
718let mat = caps.get(1).unwrap();
719assert_eq!((7, 10), (mat.start(), mat.end()));
720
721// If there was a match, Unicode mode guarantees that `title` is valid UTF-8.
722let title = str::from_utf8(&caps[1]).unwrap();
723assert_eq!("☃", title);
724```
725
726In general, if the Unicode flag is enabled in a capture group and that capture
727is part of the overall match, then the capture is *guaranteed* to be valid
728UTF-8.
729
730# Syntax
731
732The supported syntax is pretty much the same as the syntax for Unicode
733regular expressions with a few changes that make sense for matching arbitrary
734bytes:
735
7361. The `u` flag can be disabled even when disabling it might cause the regex to
737match invalid UTF-8. When the `u` flag is disabled, the regex is said to be in
738"ASCII compatible" mode.
7392. In ASCII compatible mode, neither Unicode scalar values nor Unicode
740character classes are allowed.
7413. In ASCII compatible mode, Perl character classes (`\w`, `\d` and `\s`)
742revert to their typical ASCII definition. `\w` maps to `[[:word:]]`, `\d` maps
743to `[[:digit:]]` and `\s` maps to `[[:space:]]`.
7444. In ASCII compatible mode, word boundaries use the ASCII compatible `\w` to
745determine whether a byte is a word byte or not.
7465. Hexadecimal notation can be used to specify arbitrary bytes instead of
747Unicode codepoints. For example, in ASCII compatible mode, `\xFF` matches the
748literal byte `\xFF`, while in Unicode mode, `\xFF` is a Unicode codepoint that
749matches its UTF-8 encoding of `\xC3\xBF`. Similarly for octal notation when
750enabled.
7516. In ASCII compatible mode, `.` matches any *byte* except for `\n`. When the
752`s` flag is additionally enabled, `.` matches any byte.
753
754# Performance
755
756In general, one should expect performance on `&[u8]` to be roughly similar to
757performance on `&str`.
758*/
759#[cfg(feature = "std")]
760pub mod bytes {
761 pub use crate::re_builder::bytes::*;
762 pub use crate::re_builder::set_bytes::*;
763 pub use crate::re_bytes::*;
764 pub use crate::re_set::bytes::*;
765}
766
767mod backtrack;
768mod compile;
769#[cfg(feature = "perf-dfa")]
770mod dfa;
771mod error;
772mod exec;
773mod expand;
774mod find_byte;
775mod input;
776mod literal;
777#[cfg(feature = "pattern")]
778mod pattern;
779mod pikevm;
780mod pool;
781mod prog;
782mod re_builder;
783mod re_bytes;
784mod re_set;
785mod re_trait;
786mod re_unicode;
787mod sparse;
788mod utf8;
789
790/// The `internal` module exists to support suspicious activity, such as
791/// testing different matching engines and supporting the `regex-debug` CLI
792/// utility.
793#[doc(hidden)]
794#[cfg(feature = "std")]
795pub mod internal {
796 pub use crate::compile::Compiler;
797 pub use crate::exec::{Exec, ExecBuilder};
798 pub use crate::input::{Char, CharInput, Input, InputAt};
799 pub use crate::literal::LiteralSearcher;
800 pub use crate::prog::{EmptyLook, Inst, InstRanges, Program};
801}
802