| 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 | [](https://github.com/rust-lang/regex/actions) |
| 14 | [](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 | [`std::sync::LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html |
| 109 | [`once_cell`]: https://crates.io/crates/once_cell |
| 110 | |
| 111 | ### Usage: match regular expressions on `&[u8]` |
| 112 | |
| 113 | The main API of this crate (`regex::Regex`) requires the caller to pass a |
| 114 | `&str` for searching. In Rust, an `&str` is required to be valid UTF-8, which |
| 115 | means the main API can't be used for searching arbitrary bytes. |
| 116 | |
| 117 | To match on arbitrary bytes, use the `regex::bytes::Regex` API. The API is |
| 118 | identical to the main API, except that it takes an `&[u8]` to search on instead |
| 119 | of an `&str`. The `&[u8]` APIs also permit disabling Unicode mode in the regex |
| 120 | even when the pattern would match invalid UTF-8. For example, `(?-u:.)` is |
| 121 | not allowed in `regex::Regex` but is allowed in `regex::bytes::Regex` since |
| 122 | `(?-u:.)` matches any byte except for `\n`. Conversely, `.` will match the |
| 123 | UTF-8 encoding of any Unicode scalar value except for `\n`. |
| 124 | |
| 125 | This example shows how to find all null-terminated strings in a slice of bytes: |
| 126 | |
| 127 | ```rust |
| 128 | use regex::bytes::Regex; |
| 129 | |
| 130 | let re = Regex::new(r"(?-u)(?<cstr>[^\x00]+)\x00").unwrap(); |
| 131 | let text = b"foo\xFFbar\x00baz\x00"; |
| 132 | |
| 133 | // Extract all of the strings without the null terminator from each match. |
| 134 | // The unwrap is OK here since a match requires the `cstr` capture to match. |
| 135 | let cstrs: Vec<&[u8]> = |
| 136 | re.captures_iter(text) |
| 137 | .map(|c| c.name("cstr").unwrap().as_bytes()) |
| 138 | .collect(); |
| 139 | assert_eq!(vec![&b"foo\xFFbar"[..], &b"baz"[..]], cstrs); |
| 140 | ``` |
| 141 | |
| 142 | Notice here that the `[^\x00]+` will match any *byte* except for `NUL`, |
| 143 | including bytes like `\xFF` which are not valid UTF-8. When using the main API, |
| 144 | `[^\x00]+` would instead match any valid UTF-8 sequence except for `NUL`. |
| 145 | |
| 146 | ### Usage: match multiple regular expressions simultaneously |
| 147 | |
| 148 | This demonstrates how to use a `RegexSet` to match multiple (possibly |
| 149 | overlapping) regular expressions in a single scan of the search text: |
| 150 | |
| 151 | ```rust |
| 152 | use regex::RegexSet; |
| 153 | |
| 154 | let set = RegexSet::new(&[ |
| 155 | r"\w+", |
| 156 | r"\d+", |
| 157 | r"\pL+", |
| 158 | r"foo", |
| 159 | r"bar", |
| 160 | r"barfoo", |
| 161 | r"foobar", |
| 162 | ]).unwrap(); |
| 163 | |
| 164 | // Iterate over and collect all of the matches. |
| 165 | let matches: Vec<_> = set.matches("foobar").into_iter().collect(); |
| 166 | assert_eq!(matches, vec![0, 2, 3, 4, 6]); |
| 167 | |
| 168 | // You can also test whether a particular regex matched: |
| 169 | let matches = set.matches("foobar"); |
| 170 | assert!(!matches.matched(5)); |
| 171 | assert!(matches.matched(6)); |
| 172 | ``` |
| 173 | |
| 174 | |
| 175 | ### Usage: regex internals as a library |
| 176 | |
| 177 | The [`regex-automata` directory](./regex-automata/) contains a crate that |
| 178 | exposes all the internal matching engines used by the `regex` crate. The |
| 179 | idea is that the `regex` crate exposes a simple API for 99% of use cases, but |
| 180 | `regex-automata` exposes oodles of customizable behaviors. |
| 181 | |
| 182 | [Documentation for `regex-automata`.](https://docs.rs/regex-automata) |
| 183 | |
| 184 | |
| 185 | ### Usage: a regular expression parser |
| 186 | |
| 187 | This repository contains a crate that provides a well tested regular expression |
| 188 | parser, abstract syntax and a high-level intermediate representation for |
| 189 | convenient analysis. It provides no facilities for compilation or execution. |
| 190 | This may be useful if you're implementing your own regex engine or otherwise |
| 191 | need to do analysis on the syntax of a regular expression. It is otherwise not |
| 192 | recommended for general use. |
| 193 | |
| 194 | [Documentation for `regex-syntax`.](https://docs.rs/regex-syntax) |
| 195 | |
| 196 | |
| 197 | ### Crate features |
| 198 | |
| 199 | This crate comes with several features that permit tweaking the trade-off |
| 200 | between binary size, compilation time and runtime performance. Users of this |
| 201 | crate can selectively disable Unicode tables, or choose from a variety of |
| 202 | optimizations performed by this crate to disable. |
| 203 | |
| 204 | When all of these features are disabled, runtime match performance may be much |
| 205 | worse, but if you're matching on short strings, or if high performance isn't |
| 206 | necessary, then such a configuration is perfectly serviceable. To disable |
| 207 | all such features, use the following `Cargo.toml` dependency configuration: |
| 208 | |
| 209 | ```toml |
| 210 | [dependencies.regex] |
| 211 | version = "1.3" |
| 212 | default-features = false |
| 213 | # Unless you have a specific reason not to, it's good sense to enable standard |
| 214 | # library support. It enables several optimizations and avoids spin locks. It |
| 215 | # also shouldn't meaningfully impact compile times or binary size. |
| 216 | features = ["std"] |
| 217 | ``` |
| 218 | |
| 219 | This will reduce the dependency tree of `regex` down to two crates: |
| 220 | `regex-syntax` and `regex-automata`. |
| 221 | |
| 222 | The full set of features one can disable are |
| 223 | [in the "Crate features" section of the documentation](https://docs.rs/regex/1.*/#crate-features). |
| 224 | |
| 225 | |
| 226 | ### Performance |
| 227 | |
| 228 | One of the goals of this crate is for the regex engine to be "fast." What that |
| 229 | is a somewhat nebulous goal, it is usually interpreted in one of two ways. |
| 230 | First, it means that all searches take worst case `O(m * n)` time, where |
| 231 | `m` is proportional to `len(regex)` and `n` is proportional to `len(haystack)`. |
| 232 | Second, it means that even aside from the time complexity constraint, regex |
| 233 | searches are "fast" in practice. |
| 234 | |
| 235 | While the first interpretation is pretty unambiguous, the second one remains |
| 236 | nebulous. While nebulous, it guides this crate's architecture and the sorts of |
| 237 | the trade-offs it makes. For example, here are some general architectural |
| 238 | statements that follow as a result of the goal to be "fast": |
| 239 | |
| 240 | * When given the choice between faster regex searches and faster _Rust compile |
| 241 | times_, this crate will generally choose faster regex searches. |
| 242 | * When given the choice between faster regex searches and faster _regex compile |
| 243 | times_, this crate will generally choose faster regex searches. That is, it is |
| 244 | generally acceptable for `Regex::new` to get a little slower if it means that |
| 245 | searches get faster. (This is a somewhat delicate balance to strike, because |
| 246 | the speed of `Regex::new` needs to remain somewhat reasonable. But this is why |
| 247 | one should avoid re-compiling the same regex over and over again.) |
| 248 | * When given the choice between faster regex searches and simpler API |
| 249 | design, this crate will generally choose faster regex searches. For example, |
| 250 | if one didn't care about performance, we could like get rid of both of |
| 251 | the `Regex::is_match` and `Regex::find` APIs and instead just rely on |
| 252 | `Regex::captures`. |
| 253 | |
| 254 | There are perhaps more ways that being "fast" influences things. |
| 255 | |
| 256 | While this repository used to provide its own benchmark suite, it has since |
| 257 | been moved to [rebar](https://github.com/BurntSushi/rebar). The benchmarks are |
| 258 | quite extensive, and there are many more than what is shown in rebar's README |
| 259 | (which is just limited to a "curated" set meant to compare performance between |
| 260 | regex engines). To run all of this crate's benchmarks, first start by cloning |
| 261 | and installing `rebar`: |
| 262 | |
| 263 | ```text |
| 264 | $ git clone https://github.com/BurntSushi/rebar |
| 265 | $ cd rebar |
| 266 | $ cargo install --path ./ |
| 267 | ``` |
| 268 | |
| 269 | Then build the benchmark harness for just this crate: |
| 270 | |
| 271 | ```text |
| 272 | $ rebar build -e '^rust/regex$' |
| 273 | ``` |
| 274 | |
| 275 | Run all benchmarks for this crate as tests (each benchmark is executed once to |
| 276 | ensure it works): |
| 277 | |
| 278 | ```text |
| 279 | $ rebar measure -e '^rust/regex$' -t |
| 280 | ``` |
| 281 | |
| 282 | Record measurements for all benchmarks and save them to a CSV file: |
| 283 | |
| 284 | ```text |
| 285 | $ rebar measure -e '^rust/regex$' | tee results.csv |
| 286 | ``` |
| 287 | |
| 288 | Explore benchmark timings: |
| 289 | |
| 290 | ```text |
| 291 | $ rebar cmp results.csv |
| 292 | ``` |
| 293 | |
| 294 | See the `rebar` documentation for more details on how it works and how to |
| 295 | compare results with other regex engines. |
| 296 | |
| 297 | |
| 298 | ### Hacking |
| 299 | |
| 300 | The `regex` crate is, for the most part, a pretty thin wrapper around the |
| 301 | [`meta::Regex`](https://docs.rs/regex-automata/latest/regex_automata/meta/struct.Regex.html) |
| 302 | from the |
| 303 | [`regex-automata` crate](https://docs.rs/regex-automata/latest/regex_automata/). |
| 304 | Therefore, if you're looking to work on the internals of this crate, you'll |
| 305 | likely either want to look in `regex-syntax` (for parsing) or `regex-automata` |
| 306 | (for construction of finite automata and the search routines). |
| 307 | |
| 308 | My [blog on regex internals](https://burntsushi.net/regex-internals/) |
| 309 | goes into more depth. |
| 310 | |
| 311 | |
| 312 | ### Minimum Rust version policy |
| 313 | |
| 314 | This crate's minimum supported `rustc` version is `1.65.0`. |
| 315 | |
| 316 | The policy is that the minimum Rust version required to use this crate can be |
| 317 | increased in minor version updates. For example, if regex 1.0 requires Rust |
| 318 | 1.20.0, then regex 1.0.z for all values of `z` will also require Rust 1.20.0 or |
| 319 | newer. However, regex 1.y for `y > 0` may require a newer minimum version of |
| 320 | Rust. |
| 321 | |
| 322 | |
| 323 | ### License |
| 324 | |
| 325 | This project is licensed under either of |
| 326 | |
| 327 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or |
| 328 | https://www.apache.org/licenses/LICENSE-2.0) |
| 329 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or |
| 330 | https://opensource.org/licenses/MIT) |
| 331 | |
| 332 | at your option. |
| 333 | |
| 334 | The data in `regex-syntax/src/unicode_tables/` is licensed under the Unicode |
| 335 | License Agreement |
| 336 | ([LICENSE-UNICODE](https://www.unicode.org/copyright.html#License)). |