1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 This crate provides a library for parsing, compiling, and executing regular
13 expressions. Its syntax is similar to Perl-style regular expressions, but lacks
14 a few features like look around and backreferences. In exchange, all searches
15 execute in linear time with respect to the size of the regular expression and
18 This crate's documentation provides some simple examples, describes
19 [Unicode support](#unicode) and exhaustively lists the
20 [supported syntax](#syntax).
22 For more specific details on the API for regular expressions, please see the
23 documentation for the [`Regex`](struct.Regex.html) type.
27 This crate is [on crates.io](https://crates.io/crates/regex) and can be
28 used by adding `regex` to your dependencies in your project's `Cargo.toml`.
35 and this to your crate root:
41 # Example: find a date
43 General use of regular expressions in this package involves compiling an
44 expression and then using it to search, split or replace text. For example,
45 to confirm that some text resembles a date:
49 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
50 assert!(re.is_match("2014-01-01"));
53 Notice the use of the `^` and `$` anchors. In this crate, every expression
54 is executed with an implicit `.*?` at the beginning and end, which allows
55 it to match anywhere in the text. Anchors can be used to ensure that the
56 full text matches an expression.
58 This example also demonstrates the utility of
59 [raw strings](https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals)
61 are just like regular strings except they are prefixed with an `r` and do
62 not process any escape sequences. For example, `"\\d"` is the same
63 expression as `r"\d"`.
65 # Example: Avoid compiling the same regex in a loop
67 It is an anti-pattern to compile the same regular expression in a loop
68 since compilation is typically expensive. (It takes anywhere from a few
69 microseconds to a few **milliseconds** depending on the size of the
70 regex.) Not only is compilation itself expensive, but this also prevents
71 optimizations that reuse allocations internally to the matching engines.
73 In Rust, it can sometimes be a pain to pass regular expressions around if
74 they're used from inside a helper function. Instead, we recommend using the
75 [`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that
76 regular expressions are compiled exactly once.
81 #[macro_use] extern crate lazy_static;
86 fn some_helper_function(text: &str) -> bool {
88 static ref RE: Regex = Regex::new("...").unwrap();
96 Specifically, in this example, the regex will be compiled when it is used for
97 the first time. On subsequent uses, it will reuse the previous compilation.
99 # Example: iterating over capture groups
101 This crate provides convenient iterators for matching an expression
102 repeatedly against a search string to find successive non-overlapping
103 matches. For example, to find all dates in a string and be able to access
104 them by their component pieces:
107 # extern crate regex; use regex::Regex;
109 let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
110 let text = "2012-03-14, 2013-01-01 and 2014-07-05";
111 for cap in re.captures_iter(text) {
112 println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]);
115 // Month: 03 Day: 14 Year: 2012
116 // Month: 01 Day: 01 Year: 2013
117 // Month: 07 Day: 05 Year: 2014
121 Notice that the year is in the capture group indexed at `1`. This is
122 because the *entire match* is stored in the capture group at index `0`.
124 # Example: replacement with named capture groups
126 Building on the previous example, perhaps we'd like to rearrange the date
127 formats. This can be done with text replacement. But to make the code
128 clearer, we can *name* our capture groups and use those names as variables
129 in our replacement text:
132 # extern crate regex; use regex::Regex;
134 let re = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})").unwrap();
135 let before = "2012-03-14, 2013-01-01 and 2014-07-05";
136 let after = re.replace_all(before, "$m/$d/$y");
137 assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014");
141 The `replace` methods are actually polymorphic in the replacement, which
142 provides more flexibility than is seen here. (See the documentation for
143 `Regex::replace` for more details.)
145 Note that if your regex gets complicated, you can use the `x` flag to
146 enable insignificant whitespace mode, which also lets you write comments:
149 # extern crate regex; use regex::Regex;
151 let re = Regex::new(r"(?x)
152 (?P<y>\d{4}) # the year
154 (?P<m>\d{2}) # the month
156 (?P<d>\d{2}) # the day
158 let before = "2012-03-14, 2013-01-01 and 2014-07-05";
159 let after = re.replace_all(before, "$m/$d/$y");
160 assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014");
164 If you wish to match against whitespace in this mode, you can still use `\s`,
165 `\n`, `\t`, etc. For escaping a single space character, you can use its hex
166 character code `\x20` or temporarily disable the `x` flag, e.g., `(?-x: )`.
168 # Example: match multiple regular expressions simultaneously
170 This demonstrates how to use a `RegexSet` to match multiple (possibly
171 overlapping) regular expressions in a single scan of the search text:
176 let set = RegexSet::new(&[
186 // Iterate over and collect all of the matches.
187 let matches: Vec<_> = set.matches("foobar").into_iter().collect();
188 assert_eq!(matches, vec![0, 2, 3, 4, 6]);
190 // You can also test whether a particular regex matched:
191 let matches = set.matches("foobar");
192 assert!(!matches.matched(5));
193 assert!(matches.matched(6));
196 # Pay for what you use
198 With respect to searching text with a regular expression, there are three
199 questions that can be asked:
201 1. Does the text match this expression?
202 2. If so, where does it match?
203 3. Where did the capturing groups match?
205 Generally speaking, this crate could provide a function to answer only #3,
206 which would subsume #1 and #2 automatically. However, it can be significantly
207 more expensive to compute the location of capturing group matches, so it's best
208 not to do it if you don't need to.
210 Therefore, only use what you need. For example, don't use `find` if you
211 only need to test if an expression matches a string. (Use `is_match`
216 This implementation executes regular expressions **only** on valid UTF-8
217 while exposing match locations as byte indices into the search string.
219 Only simple case folding is supported. Namely, when matching
220 case-insensitively, the characters are first mapped using the "simple" case
221 folding rules defined by Unicode.
223 Regular expressions themselves are **only** interpreted as a sequence of
224 Unicode scalar values. This means you can use Unicode characters directly
228 # extern crate regex; use regex::Regex;
230 let re = Regex::new(r"(?i)Δ+").unwrap();
231 let mat = re.find("ΔδΔ").unwrap();
232 assert_eq!((mat.start(), mat.end()), (0, 6));
236 Most features of the regular expressions in this crate are Unicode aware. Here
239 * `.` will match any valid UTF-8 encoded Unicode scalar value except for `\n`.
240 (To also match `\n`, enable the `s` flag, e.g., `(?s:.)`.)
241 * `\w`, `\d` and `\s` are Unicode aware. For example, `\s` will match all forms
242 of whitespace categorized by Unicode.
243 * `\b` matches a Unicode word boundary.
244 * Negated character classes like `[^a]` match all Unicode scalar values except
246 * `^` and `$` are **not** Unicode aware in multi-line mode. Namely, they only
247 recognize `\n` and not any of the other forms of line terminators defined
250 Unicode general categories, scripts, script extensions, ages and a smattering
251 of boolean properties are available as character classes. For example, you can
252 match a sequence of numerals, Greek or Cherokee letters:
255 # extern crate regex; use regex::Regex;
257 let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap();
258 let mat = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap();
259 assert_eq!((mat.start(), mat.end()), (3, 23));
263 For a more detailed breakdown of Unicode support with respect to
264 [UTS#18](http://unicode.org/reports/tr18/),
266 [UNICODE](https://github.com/rust-lang/regex/blob/master/UNICODE.md)
267 document in the root of the regex repository.
269 # Opt out of Unicode support
271 The `bytes` sub-module provides a `Regex` type that can be used to match
272 on `&[u8]`. By default, text is interpreted as UTF-8 just like it is with
273 the main `Regex` type. However, this behavior can be disabled by turning
274 off the `u` flag, even if doing so could result in matching invalid UTF-8.
275 For example, when the `u` flag is disabled, `.` will match any byte instead
276 of any Unicode scalar value.
278 Disabling the `u` flag is also possible with the standard `&str`-based `Regex`
279 type, but it is only allowed where the UTF-8 invariant is maintained. For
280 example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an
281 `&str`-based `Regex`, but `(?-u:\xFF)` will attempt to match the raw byte
282 `\xFF`, which is invalid UTF-8 and therefore is illegal in `&str`-based
287 The syntax supported in this crate is documented below.
289 Note that the regular expression parser and abstract syntax are exposed in
290 a separate crate, [`regex-syntax`](https://docs.rs/regex-syntax).
292 ## Matching one character
295 . any character except new line (includes new line with s flag)
298 \pN One-letter name Unicode character class
299 \p{Greek} Unicode character class (general category or script)
300 \PN Negated one-letter name Unicode character class
301 \P{Greek} negated Unicode character class (general category or script)
304 ### Character classes
307 [xyz] A character class matching either x, y or z (union).
308 [^xyz] A character class matching any character except x, y and z.
309 [a-z] A character class matching any character in range a-z.
310 [[:alpha:]] ASCII character class ([A-Za-z])
311 [[:^alpha:]] Negated ASCII character class ([^A-Za-z])
312 [x[^xyz]] Nested/grouping character class (matching any character except y and z)
313 [a-y&&xyz] Intersection (matching x or y)
314 [0-9&&[^4]] Subtraction using intersection and negation (matching 0-9 except 4)
315 [0-9--4] Direct subtraction (matching 0-9 except 4)
316 [a-g~~b-h] Symmetric difference (matching `a` and `h` only)
317 [\[\]] Escaping in character classes (matching [ or ])
320 Any named character class may appear inside a bracketed `[...]` character
321 class. For example, `[\p{Greek}[:digit:]]` matches any Greek or ASCII
322 digit. `[\p{Greek}&&\pL]` matches Greek letters.
324 Precedence in character classes, from most binding to least:
326 1. Ranges: `a-cd` == `[a-c]d`
327 2. Union: `ab&&bc` == `[ab]&&[bc]`
328 3. Intersection: `^a-z&&b` == `^[a-z&&b]`
334 xy concatenation (x followed by y)
335 x|y alternation (x or y, prefer x)
341 x* zero or more of x (greedy)
342 x+ one or more of x (greedy)
343 x? zero or one of x (greedy)
344 x*? zero or more of x (ungreedy/lazy)
345 x+? one or more of x (ungreedy/lazy)
346 x?? zero or one of x (ungreedy/lazy)
347 x{n,m} at least n x and at most m x (greedy)
348 x{n,} at least n x (greedy)
350 x{n,m}? at least n x and at most m x (ungreedy/lazy)
351 x{n,}? at least n x (ungreedy/lazy)
358 ^ the beginning of text (or start-of-line with multi-line mode)
359 $ the end of text (or end-of-line with multi-line mode)
360 \A only the beginning of text (even with multi-line mode enabled)
361 \z only the end of text (even with multi-line mode enabled)
362 \b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
363 \B not a Unicode word boundary
366 ## Grouping and flags
369 (exp) numbered capture group (indexed by opening parenthesis)
370 (?P<name>exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
371 (?:exp) non-capturing group
372 (?flags) set flags within current group
373 (?flags:exp) set flags for exp (non-capturing)
376 Flags are each a single character. For example, `(?x)` sets the flag `x`
377 and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
378 the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
379 the `x` flag and clears the `y` flag.
381 All flags are by default disabled unless stated otherwise. They are:
384 i case-insensitive: letters match both upper and lower case
385 m multi-line mode: ^ and $ match begin/end of line
386 s allow . to match \n
387 U swap the meaning of x* and x*?
388 u Unicode support (enabled by default)
389 x ignore whitespace and allow line comments (starting with `#`)
392 Flags can be toggled within a pattern. Here's an example that matches
393 case-insensitively for the first part but case-sensitively for the second part:
396 # extern crate regex; use regex::Regex;
398 let re = Regex::new(r"(?i)a+(?-i)b+").unwrap();
399 let cap = re.captures("AaAaAbbBBBb").unwrap();
400 assert_eq!(&cap[0], "AaAaAbb");
404 Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
407 Multi-line mode means `^` and `$` no longer match just at the beginning/end of
408 the input, but at the beginning/end of lines:
412 let re = Regex::new(r"(?m)^line \d+").unwrap();
413 let m = re.find("line one\nline 2\n").unwrap();
414 assert_eq!(m.as_str(), "line 2");
417 Note that `^` matches after new lines, even at the end of input:
421 let re = Regex::new(r"(?m)^").unwrap();
422 let m = re.find_iter("test\n").last().unwrap();
423 assert_eq!((m.start(), m.end()), (5, 5));
426 Here is an example that uses an ASCII word boundary instead of a Unicode
430 # extern crate regex; use regex::Regex;
432 let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap();
433 let cap = re.captures("$$abc$$").unwrap();
434 assert_eq!(&cap[0], "abc");
441 \* literal *, works for any punctuation character: \.+*?()|[]{}^$
447 \v vertical tab (\x0B)
448 \123 octal character code (up to three digits) (when enabled)
449 \x7F hex character code (exactly two digits)
450 \x{10FFFF} any hex character code corresponding to a Unicode code point
451 \u007F hex character code (exactly four digits)
452 \u{7F} any hex character code corresponding to a Unicode code point
453 \U0000007F hex character code (exactly eight digits)
454 \U{7F} any hex character code corresponding to a Unicode code point
457 ## Perl character classes (Unicode friendly)
459 These classes are based on the definitions provided in
460 [UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties):
465 \s whitespace (\p{White_Space})
467 \w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
468 \W not word character
471 ## ASCII character classes
474 [[:alnum:]] alphanumeric ([0-9A-Za-z])
475 [[:alpha:]] alphabetic ([A-Za-z])
476 [[:ascii:]] ASCII ([\x00-\x7F])
477 [[:blank:]] blank ([\t ])
478 [[:cntrl:]] control ([\x00-\x1F\x7F])
479 [[:digit:]] digits ([0-9])
480 [[:graph:]] graphical ([!-~])
481 [[:lower:]] lower case ([a-z])
482 [[:print:]] printable ([ -~])
483 [[:punct:]] punctuation ([!-/:-@\[-`{-~])
484 [[:space:]] whitespace ([\t\n\v\f\r ])
485 [[:upper:]] upper case ([A-Z])
486 [[:word:]] word characters ([0-9A-Za-z_])
487 [[:xdigit:]] hex digit ([0-9A-Fa-f])
492 This crate can handle both untrusted regular expressions and untrusted
495 Untrusted regular expressions are handled by capping the size of a compiled
497 (See [`RegexBuilder::size_limit`](struct.RegexBuilder.html#method.size_limit).)
498 Without this, it would be trivial for an attacker to exhaust your system's
499 memory with expressions like `a{100}{100}{100}`.
501 Untrusted search text is allowed because the matching engine(s) in this
502 crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search
503 text`), which means there's no way to cause exponential blow-up like with
504 some other regular expression engines. (We pay for this by disallowing
505 features like arbitrary look-ahead and backreferences.)
507 When a DFA is used, pathological cases with exponential state blow-up are
508 avoided by constructing the DFA lazily or in an "online" manner. Therefore,
509 at most one new state can be created for each byte of input. This satisfies
510 our time complexity guarantees, but can lead to memory growth
511 proportional to the size of the input. As a stopgap, the DFA is only
512 allowed to store a fixed number of states. When the limit is reached, its
513 states are wiped and continues on, possibly duplicating previous work. If
514 the limit is reached too frequently, it gives up and hands control off to
515 another matching engine with fixed memory requirements.
516 (The DFA size limit can also be tweaked. See
517 [`RegexBuilder::dfa_size_limit`](struct.RegexBuilder.html#method.dfa_size_limit).)
520 #![deny(missing_docs)]
521 #![allow(ellipsis_inclusive_range_patterns)]
522 #![cfg_attr(test, deny(warnings))]
523 #![cfg_attr(feature = "pattern", feature(pattern))]
525 #[cfg(not(feature = "use_std"))]
526 compile_error
!("`use_std` feature is currently required to build this crate");
528 extern crate aho_corasick
;
530 extern crate thread_local
;
533 extern crate quickcheck
;
534 extern crate regex_syntax
as syntax
;
535 extern crate utf8_ranges
;
537 extern crate doc_comment
;
540 doc_comment
::doctest
!("../README.md");
542 #[cfg(feature = "use_std")]
543 pub use error
::Error
;
544 #[cfg(feature = "use_std")]
545 pub use re_builder
::unicode
::*;
546 #[cfg(feature = "use_std")]
547 pub use re_builder
::set_unicode
::*;
548 #[cfg(feature = "use_std")]
549 pub use re_set
::unicode
::*;
550 #[cfg(feature = "use_std")]
551 #[cfg(feature = "use_std")]
552 pub use re_unicode
::{
553 Regex
, Match
, Captures
,
554 CaptureNames
, Matches
, CaptureMatches
, SubCaptureMatches
,
555 CaptureLocations
, Locations
,
556 Replacer
, ReplacerRef
, NoExpand
, Split
, SplitN
,
561 Match regular expressions on arbitrary bytes.
563 This module provides a nearly identical API to the one found in the
564 top-level of this crate. There are two important differences:
566 1. Matching is done on `&[u8]` instead of `&str`. Additionally, `Vec<u8>`
567 is used where `String` would have been used.
568 2. Unicode support can be disabled even when disabling it would result in
569 matching invalid UTF-8 bytes.
571 # Example: match null terminated string
573 This shows how to find all null-terminated strings in a slice of bytes:
576 # use regex::bytes::Regex;
577 let re = Regex::new(r"(?-u)(?P<cstr>[^\x00]+)\x00").unwrap();
578 let text = b"foo\x00bar\x00baz\x00";
580 // Extract all of the strings without the null terminator from each match.
581 // The unwrap is OK here since a match requires the `cstr` capture to match.
582 let cstrs: Vec<&[u8]> =
583 re.captures_iter(text)
584 .map(|c| c.name("cstr").unwrap().as_bytes())
586 assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs);
589 # Example: selectively enable Unicode support
591 This shows how to match an arbitrary byte pattern followed by a UTF-8 encoded
592 string (e.g., to extract a title from a Matroska file):
596 # use regex::bytes::Regex;
598 r"(?-u)\x7b\xa9(?:[\x80-\xfe]|[\x40-\xff].)(?u:(.*))"
600 let text = b"\x12\xd0\x3b\x5f\x7b\xa9\x85\xe2\x98\x83\x80\x98\x54\x76\x68\x65";
601 let caps = re.captures(text).unwrap();
603 // Notice that despite the `.*` at the end, it will only match valid UTF-8
604 // because Unicode mode was enabled with the `u` flag. Without the `u` flag,
605 // the `.*` would match the rest of the bytes.
606 let mat = caps.get(1).unwrap();
607 assert_eq!((7, 10), (mat.start(), mat.end()));
609 // If there was a match, Unicode mode guarantees that `title` is valid UTF-8.
610 let title = str::from_utf8(&caps[1]).unwrap();
611 assert_eq!("☃", title);
614 In general, if the Unicode flag is enabled in a capture group and that capture
615 is part of the overall match, then the capture is *guaranteed* to be valid
620 The supported syntax is pretty much the same as the syntax for Unicode
621 regular expressions with a few changes that make sense for matching arbitrary
624 1. The `u` flag can be disabled even when disabling it might cause the regex to
625 match invalid UTF-8. When the `u` flag is disabled, the regex is said to be in
626 "ASCII compatible" mode.
627 2. In ASCII compatible mode, neither Unicode scalar values nor Unicode
628 character classes are allowed.
629 3. In ASCII compatible mode, Perl character classes (`\w`, `\d` and `\s`)
630 revert to their typical ASCII definition. `\w` maps to `[[:word:]]`, `\d` maps
631 to `[[:digit:]]` and `\s` maps to `[[:space:]]`.
632 4. In ASCII compatible mode, word boundaries use the ASCII compatible `\w` to
633 determine whether a byte is a word byte or not.
634 5. Hexadecimal notation can be used to specify arbitrary bytes instead of
635 Unicode codepoints. For example, in ASCII compatible mode, `\xFF` matches the
636 literal byte `\xFF`, while in Unicode mode, `\xFF` is a Unicode codepoint that
637 matches its UTF-8 encoding of `\xC3\xBF`. Similarly for octal notation when
639 6. `.` matches any *byte* except for `\n` instead of any Unicode scalar value.
640 When the `s` flag is enabled, `.` matches any byte.
644 In general, one should expect performance on `&[u8]` to be roughly similar to
645 performance on `&str`.
647 #[cfg(feature = "use_std")]
649 pub use re_builder
::bytes
::*;
650 pub use re_builder
::set_bytes
::*;
652 pub use re_set
::bytes
::*;
665 #[cfg(feature = "pattern")]
675 #[cfg(any(regex_runtime_teddy_ssse3, regex_runtime_teddy_avx2))]
678 /// The `internal` module exists to support suspicious activity, such as
679 /// testing different matching engines and supporting the `regex-debug` CLI
682 #[cfg(feature = "use_std")]
684 pub use compile
::Compiler
;
685 pub use exec
::{Exec, ExecBuilder}
;
686 pub use input
::{Char, Input, CharInput, InputAt}
;
687 pub use literal
::LiteralSearcher
;
688 pub use prog
::{Program, Inst, EmptyLook, InstRanges}
;