Debian Codegraph @

debian/rust-vendor/regex/README.md

raw
1 regex
2 =====
3 This crate provides routines for searching strings for matches of a [regular
4 expression] (aka "regex"). The regex syntax supported by this crate is similar
5 to other regex engines, but it lacks several features that are not known how to
6 implement efficiently. This includes, but is not limited to, look-around and
7 backreferences. In exchange, all regex searches in this crate have worst case
8 `O(m * n)` time complexity, where `m` is proportional to the size of the regex
9 and `n` is proportional to the size of the string being searched.
10
11 [regular expression]: https://en.wikipedia.org/wiki/Regular_expression
12
13 [![Build status](https://github.com/rust-lang/regex/workflows/ci/badge.svg)](https://github.com/rust-lang/regex/actions)
14 [![Crates.io](https://img.shields.io/crates/v/regex.svg)](https://crates.io/crates/regex)
15
16 ### Documentation
17
18 [Module documentation with examples](https://docs.rs/regex).
19 The module documentation also includes a comprehensive description of the
20 syntax supported.
21
22 Documentation with examples for the various matching functions and iterators
23 can be found on the
24 [`Regex` type](https://docs.rs/regex/*/regex/struct.Regex.html).
25
26 ### Usage
27
28 To bring this crate into your repository, either add `regex` to your
29 `Cargo.toml`, or run `cargo add regex`.
30
31 Here's a simple example that matches a date in YYYY-MM-DD format and prints the
32 year, month and day:
33
34 ```rust
35 use regex::Regex;
36
37 fn main() {
38 let re = Regex::new(r"(?x)
39 (?P<year>\d{4}) # the year
40 -
41 (?P<month>\d{2}) # the month
42 -
43 (?P<day>\d{2}) # the day
44 ").unwrap();
45
46 let caps = re.captures("2010-03-14").unwrap();
47 assert_eq!("2010", &caps["year"]);
48 assert_eq!("03", &caps["month"]);
49 assert_eq!("14", &caps["day"]);
50 }
51 ```
52
53 If you have lots of dates in text that you'd like to iterate over, then it's
54 easy to adapt the above example with an iterator:
55
56 ```rust
57 use regex::Regex;
58
59 fn main() {
60 let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
61 let hay = "On 2010-03-14, foo happened. On 2014-10-14, bar happened.";
62
63 let mut dates = vec![];
64 for (_, [year, month, day]) in re.captures_iter(hay).map(|c| c.extract()) {
65 dates.push((year, month, day));
66 }
67 assert_eq!(dates, vec![
68 ("2010", "03", "14"),
69 ("2014", "10", "14"),
70 ]);
71 }
72 ```
73
74 ### Usage: Avoid compiling the same regex in a loop
75
76 It is an anti-pattern to compile the same regular expression in a loop since
77 compilation is typically expensive. (It takes anywhere from a few microseconds
78 to a few **milliseconds** depending on the size of the regex.) Not only is
79 compilation itself expensive, but this also prevents optimizations that reuse
80 allocations internally to the matching engines.
81
82 In Rust, it can sometimes be a pain to pass regular expressions around if
83 they're used from inside a helper function. Instead, we recommend using
84 [`std::sync::LazyLock`], or the [`once_cell`] crate,
85 if you can't use the standard library.
86
87 This example shows how to use `std::sync::LazyLock`:
88
89 ```rust
90 use std::sync::LazyLock;
91
92 use regex::Regex;
93
94 fn some_helper_function(haystack: &str) -> bool {
95 static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"...").unwrap());
96 RE.is_match(haystack)
97 }
98
99 fn main() {
100 assert!(some_helper_function("abc"));
101 assert!(!some_helper_function("ac"));
102 }
103 ```
104
105 Specifically, in this example, the regex will be compiled when it is used for
106 the first time. On subsequent uses, it will reuse the previous compilation.
107
108 The [`regex!`] macro can also be used, which handles lazy compilation.
109
110 [`std::sync::LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html
111 [`once_cell`]: https://crates.io/crates/once_cell
112 [`regex!`]: https://docs.rs/regex/*/regex/macro.regex.html
113
114 ### Usage: match regular expressions on `&[u8]`
115
116 The main API of this crate (`regex::Regex`) requires the caller to pass a
117 `&str` for searching. In Rust, an `&str` is required to be valid UTF-8, which
118 means the main API can't be used for searching arbitrary bytes.
119
120 To match on arbitrary bytes, use the `regex::bytes::Regex` API. The API is
121 identical to the main API, except that it takes an `&[u8]` to search on instead
122 of an `&str`. The `&[u8]` APIs also permit disabling Unicode mode in the regex
123 even when the pattern would match invalid UTF-8. For example, `(?-u:.)` is
124 not allowed in `regex::Regex` but is allowed in `regex::bytes::Regex` since
125 `(?-u:.)` matches any byte except for `\n`. Conversely, `.` will match the
126 UTF-8 encoding of any Unicode scalar value except for `\n`.
127
128 This example shows how to find all null-terminated strings in a slice of bytes:
129
130 ```rust
131 use regex::bytes::Regex;
132
133 let re = Regex::new(r"(?-u)(?<cstr>[^\x00]+)\x00").unwrap();
134 let text = b"foo\xFFbar\x00baz\x00";
135
136 // Extract all of the strings without the null terminator from each match.
137 // The unwrap is OK here since a match requires the `cstr` capture to match.
138 let cstrs: Vec<&[u8]> =
139 re.captures_iter(text)
140 .map(|c| c.name("cstr").unwrap().as_bytes())
141 .collect();
142 assert_eq!(vec![&b"foo\xFFbar"[..], &b"baz"[..]], cstrs);
143 ```
144
145 Notice here that the `[^\x00]+` will match any *byte* except for `NUL`,
146 including bytes like `\xFF` which are not valid UTF-8. When using the main API,
147 `[^\x00]+` would instead match any valid UTF-8 sequence except for `NUL`.
148
149 ### Usage: match multiple regular expressions simultaneously
150
151 This demonstrates how to use a `RegexSet` to match multiple (possibly
152 overlapping) regular expressions in a single scan of the search text:
153
154 ```rust
155 use regex::RegexSet;
156
157 let set = RegexSet::new(&[
158 r"\w+",
159 r"\d+",
160 r"\pL+",
161 r"foo",
162 r"bar",
163 r"barfoo",
164 r"foobar",
165 ]).unwrap();
166
167 // Iterate over and collect all of the matches.
168 let matches: Vec<_> = set.matches("foobar").into_iter().collect();
169 assert_eq!(matches, vec![0, 2, 3, 4, 6]);
170
171 // You can also test whether a particular regex matched:
172 let matches = set.matches("foobar");
173 assert!(!matches.matched(5));
174 assert!(matches.matched(6));
175 ```
176
177
178 ### Usage: regex internals as a library
179
180 The [`regex-automata` directory](./regex-automata/) contains a crate that
181 exposes all the internal matching engines used by the `regex` crate. The
182 idea is that the `regex` crate exposes a simple API for 99% of use cases, but
183 `regex-automata` exposes oodles of customizable behaviors.
184
185 [Documentation for `regex-automata`.](https://docs.rs/regex-automata)
186
187
188 ### Usage: a regular expression parser
189
190 This repository contains a crate that provides a well tested regular expression
191 parser, abstract syntax and a high-level intermediate representation for
192 convenient analysis. It provides no facilities for compilation or execution.
193 This may be useful if you're implementing your own regex engine or otherwise
194 need to do analysis on the syntax of a regular expression. It is otherwise not
195 recommended for general use.
196
197 [Documentation for `regex-syntax`.](https://docs.rs/regex-syntax)
198
199
200 ### Crate features
201
202 This crate comes with several features that permit tweaking the trade-off
203 between binary size, compilation time and runtime performance. Users of this
204 crate can selectively disable Unicode tables, or choose from a variety of
205 optimizations performed by this crate to disable.
206
207 When all of these features are disabled, runtime match performance may be much
208 worse, but if you're matching on short strings, or if high performance isn't
209 necessary, then such a configuration is perfectly serviceable. To disable
210 all such features, use the following `Cargo.toml` dependency configuration:
211
212 ```toml
213 [dependencies.regex]
214 version = "1.3"
215 default-features = false
216 # Unless you have a specific reason not to, it's good sense to enable standard
217 # library support. It enables several optimizations and avoids spin locks. It
218 # also shouldn't meaningfully impact compile times or binary size.
219 features = ["std"]
220 ```
221
222 This will reduce the dependency tree of `regex` down to two crates:
223 `regex-syntax` and `regex-automata`.
224
225 The full set of features one can disable are
226 [in the "Crate features" section of the documentation](https://docs.rs/regex/1.*/#crate-features).
227
228
229 ### Performance
230
231 One of the goals of this crate is for the regex engine to be "fast." What that
232 is a somewhat nebulous goal, it is usually interpreted in one of two ways.
233 First, it means that all searches take worst case `O(m * n)` time, where
234 `m` is proportional to `len(regex)` and `n` is proportional to `len(haystack)`.
235 Second, it means that even aside from the time complexity constraint, regex
236 searches are "fast" in practice.
237
238 While the first interpretation is pretty unambiguous, the second one remains
239 nebulous. While nebulous, it guides this crate's architecture and the sorts of
240 the trade-offs it makes. For example, here are some general architectural
241 statements that follow as a result of the goal to be "fast":
242
243 * When given the choice between faster regex searches and faster _Rust compile
244 times_, this crate will generally choose faster regex searches.
245 * When given the choice between faster regex searches and faster _regex compile
246 times_, this crate will generally choose faster regex searches. That is, it is
247 generally acceptable for `Regex::new` to get a little slower if it means that
248 searches get faster. (This is a somewhat delicate balance to strike, because
249 the speed of `Regex::new` needs to remain somewhat reasonable. But this is why
250 one should avoid re-compiling the same regex over and over again.)
251 * When given the choice between faster regex searches and simpler API
252 design, this crate will generally choose faster regex searches. For example,
253 if one didn't care about performance, we could like get rid of both of
254 the `Regex::is_match` and `Regex::find` APIs and instead just rely on
255 `Regex::captures`.
256
257 There are perhaps more ways that being "fast" influences things.
258
259 While this repository used to provide its own benchmark suite, it has since
260 been moved to [rebar](https://github.com/BurntSushi/rebar). The benchmarks are
261 quite extensive, and there are many more than what is shown in rebar's README
262 (which is just limited to a "curated" set meant to compare performance between
263 regex engines). To run all of this crate's benchmarks, first start by cloning
264 and installing `rebar`:
265
266 ```text
267 $ git clone https://github.com/BurntSushi/rebar
268 $ cd rebar
269 $ cargo install --path ./
270 ```
271
272 Then build the benchmark harness for just this crate:
273
274 ```text
275 $ rebar build -e '^rust/regex$'
276 ```
277
278 Run all benchmarks for this crate as tests (each benchmark is executed once to
279 ensure it works):
280
281 ```text
282 $ rebar measure -e '^rust/regex$' -t
283 ```
284
285 Record measurements for all benchmarks and save them to a CSV file:
286
287 ```text
288 $ rebar measure -e '^rust/regex$' | tee results.csv
289 ```
290
291 Explore benchmark timings:
292
293 ```text
294 $ rebar cmp results.csv
295 ```
296
297 See the `rebar` documentation for more details on how it works and how to
298 compare results with other regex engines.
299
300
301 ### Hacking
302
303 The `regex` crate is, for the most part, a pretty thin wrapper around the
304 [`meta::Regex`](https://docs.rs/regex-automata/latest/regex_automata/meta/struct.Regex.html)
305 from the
306 [`regex-automata` crate](https://docs.rs/regex-automata/latest/regex_automata/).
307 Therefore, if you're looking to work on the internals of this crate, you'll
308 likely either want to look in `regex-syntax` (for parsing) or `regex-automata`
309 (for construction of finite automata and the search routines).
310
311 My [blog on regex internals](https://burntsushi.net/regex-internals/)
312 goes into more depth.
313
314
315 ### Minimum Rust version policy
316
317 This crate's minimum supported `rustc` version is `1.65.0`.
318
319 The policy is that the minimum Rust version required to use this crate can be
320 increased in minor version updates. For example, if regex 1.0 requires Rust
321 1.20.0, then regex 1.0.z for all values of `z` will also require Rust 1.20.0 or
322 newer. However, regex 1.y for `y > 0` may require a newer minimum version of
323 Rust.
324
325
326 ### License
327
328 This project is licensed under either of
329
330 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
331 https://www.apache.org/licenses/LICENSE-2.0)
332 * MIT license ([LICENSE-MIT](LICENSE-MIT) or
333 https://opensource.org/licenses/MIT)
334
335 at your option.
336
337 The data in `regex-syntax/src/unicode_tables/` is licensed under the Unicode
338 License Agreement
339 ([LICENSE-UNICODE](https://www.unicode.org/copyright.html#License)).