[][src]Crate regex






regex = "1"

If you're using Rust 2015, then you'll also need to add it to your crate root:

extern crate regex;

Example: find a date


use regex::Regex;



Example: Avoid compiling the same regex in a loop



For example:

#[macro_use] extern crate lazy_static;
extern crate regex;

use regex::Regex;

fn some_helper_function(text: &str) -> bool {
    lazy_static! {

fn main() {}


Example: iterating over capture groups


for cap in re.captures_iter(text) {
// Output:
// Month: 03 Day: 14 Year: 2012
// Month: 01 Day: 01 Year: 2013
// Month: 07 Day: 05 Year: 2014


Example: replacement with named capture groups







Example: match multiple regular expressions simultaneously


use regex::RegexSet;

let set = RegexSet::new(&[

// Iterate over and collect all of the matches.

// You can also test whether a particular regex matched:
let matches = set.matches("foobar");

Pay for what you use


  1. Does the text match this expression?
  2. If so, where does it match?
  3. Where did the capturing groups match?




This implementation executes regular expressions only on valid UTF-8 while exposing match locations as byte indices into the search string. (To relax this restriction, use the bytes sub-module.)





  • \b matches a Unicode word boundary.




Opt out of Unicode support



Finally, since Unicode support requires bundling large Unicode data tables, this crate exposes knobs to disable the compilation of those data tables, which can be useful for shrinking binary size and reducing compilation times. For details on how to do that, see the section on crate features.


The syntax supported in this crate is documented below.


Matching one character

\d            digit (\p{Nd})
\D            not digit
\pN           One-letter name Unicode character class
\PN           Negated one-letter name Unicode character class

Character classes



Precedence in character classes, from most binding to least:

  4. Negation


xy    concatenation (x followed by y)
x|y   alternation (x or y, prefer x)


x*        zero or more of x (greedy)
x+        one or more of x (greedy)
x?        zero or one of x (greedy)
x{n,}     at least n x (greedy)
x{n}      exactly n x
x{n}?     exactly n x

Empty matches

\B    not a Unicode word boundary

Grouping and flags

(exp)          numbered capture group (indexed by opening parenthesis)
(?:exp)        non-capturing group
(?flags)       set flags within current group



i     case-insensitive: letters match both upper and lower case
s     allow . to match \n
U     swap the meaning of x* and x*?
u     Unicode support (enabled by default)










Escape sequences

\a          bell (\x07)
\f          form feed (\x0C)
\t          horizontal tab
\n          new line
\r          carriage return
\v          vertical tab (\x0B)
\x7F        hex character code (exactly two digits)
\u007F      hex character code (exactly four digits)
\U0000007F  hex character code (exactly eight digits)

Perl character classes (Unicode friendly)


\d     digit (\p{Nd})
\D     not digit
\s     whitespace (\p{White_Space})
\S     not whitespace
\W     not word character

ASCII character classes


Crate features

By default, this crate tries pretty hard to make regex matching both as fast as possible and as correct as it can be, within reason. This means that there is a lot of code dedicated to performance, the handling of Unicode data and the Unicode data itself. Overall, this leads to more dependencies, larger binaries and longer compile times. This trade off may not be appropriate in all cases, and indeed, even when all Unicode and performance features are disabled, one is still left with a perfectly serviceable regex engine that will work well in many cases.

This crate exposes a number of features for controlling that trade off. Some of these features are strictly performance oriented, such that disabling them won't result in a loss of functionality, but may result in worse performance. Other features, such as the ones controlling the presence or absence of Unicode data, can result in a loss of functionality. For example, if one disables the unicode-case feature (described below), then compiling the regex (?i)a will fail since Unicode case insensitivity is enabled by default. Instead, callers must use (?i-u)a instead to disable Unicode case folding. Stated differently, enabling or disabling any of the features below can only add or subtract from the total set of valid regular expressions. Enabling or disabling a feature will never modify the match semantics of a regular expression.

All features below are enabled by default.

Ecosystem features

  • std - When enabled, this will cause regex to use the standard library. Currently, disabling this feature will always result in a compilation error. It is intended to add alloc-only support to regex in the future.

Performance features

  • perf - Enables all performance related features. This feature is enabled by default and will always cover all features that improve performance, even if more are added in the future.
  • perf-cache - Enables the use of very fast thread safe caching for internal match state. When this is disabled, caching is still used, but with a slower and simpler implementation. Disabling this drops the thread_local and lazy_static dependencies.
  • perf-dfa - Enables the use of a lazy DFA for matching. The lazy DFA is used to compile portions of a regex to a very fast DFA on an as-needed basis. This can result in substantial speedups, usually by an order of magnitude on large haystacks. The lazy DFA does not bring in any new dependencies, but it can make compile times longer.
  • perf-inline - Enables the use of aggressive inlining inside match routines. This reduces the overhead of each match. The aggressive inlining, however, increases compile times and binary size.
  • perf-literal - Enables the use of literal optimizations for speeding up matches. In some cases, literal optimizations can result in speedups of several orders of magnitude. Disabling this drops the aho-corasick and memchr dependencies.

Unicode features

  • unicode - Enables all Unicode features. This feature is enabled by default, and will always cover all Unicode features, even if more are added in the future.
  • unicode-age - Provide the data for the Unicode Age property. This makes it possible to use classes like \p{Age:6.0} to refer to all codepoints first introduced in Unicode 6.0
  • unicode-bool - Provide the data for numerous Unicode boolean properties. The full list is not included here, but contains properties like Alphabetic, Emoji, Lowercase, Math, Uppercase and White_Space.
  • unicode-case - Provide the data for case insensitive matching using Unicode's "simple loose matches" specification.
  • unicode-gencat - Provide the data for Uncode general categories. This includes, but is not limited to, Decimal_Number, Letter, Math_Symbol, Number and Punctuation.
  • unicode-perl - Provide the data for supporting the Unicode-aware Perl character classes, corresponding to \w, \s and \d. This is also necessary for using Unicode-aware word boundary assertions. Note that if this feature is disabled, the \s and \d character classes are still available if the unicode-bool and unicode-gencat features are enabled, respectively.
  • unicode-script - Provide the data for Unicode scripts and script extensions. This includes, but is not limited to, Arabic, Cyrillic, Hebrew, Latin and Thai.
  • unicode-segment - Provide the data necessary to provide the properties used to implement the Unicode text segmentation algorithms. This enables using classes like \p{gcb=Extend}, \p{wb=Katakana} and \p{sb=ATerm}.

Untrusted input







Match regular expressions on arbitrary bytes.







An iterator over the names of all possible captures.


Captures represents a group of captured strings for a single match.


Match represents a single match of a regex in a haystack.




NoExpand indicates literal string replacement.


A compiled regular expression for matching Unicode strings.


A configurable builder for a regular expression.




A configurable builder for a set of regular expressions.


By-reference adaptor for a Replacer


A set of matches returned by a regex set.






Yields all substrings delimited by a regular expression match.


Yields at most N substrings delimited by a regular expression match.





An error that occurred during parsing or compiling a regular expression.






Escapes all regular expression meta characters in text.