A fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python
open sourceBSD-3-Clauseself-hostablefree
RE2 is Google's C++ regular expression library, built so that patterns from untrusted users can run without risk: matching time is linear in the length of the input, and the parser, compiler and matchers work within a configurable memory budget and avoid recursion, so they fail gracefully instead of overflowing the stack. It accepts most Perl syntax, or POSIX egrep syntax with leftmost-longest matching, but leaves out constructs only backtracking can implement, such as backreferences and look-around assertions. It has been used in production at Google since 2006; the official Python wrapper is google-re2 on PyPI, and other languages have wrappers, including the Ruby gem re2. Go's regexp package and Rust's regex crate follow the same design and syntax without sharing its code.
Problems it solves
- let users type their own regex search patterns without risking a ReDoS attack
- one bad regular expression pegged a CPU and took our service down
- I need regex matching that is guaranteed to run in linear time in the size of the input
- cap how much memory compiling and running a regular expression can use
- run regular expressions from config files or customers safely in a C++ server
- Python's re module hangs forever on certain patterns and inputs
- extract regex submatches straight into integers and strings in C++
- a regex engine that many threads can share at once
- POSIX leftmost-longest matching for egrep-style patterns in my program
- our log pipeline's backtracking regex library chokes on very long lines
- a regex library whose deep nesting can't overflow the stack
Features
- match time linear in the length of the input
- configurable memory budget for parsing, compiling and matching
- no recursion, so no stack overflow
- Perl-mode and POSIX-mode syntax
- FullMatch and PartialMatch
- submatch extraction into strings, integers and string views
- precompiled RE2 objects for reuse
- UTF-8 and Latin-1 input
- optional ICU for more Unicode property names
- builds with make, CMake or Bazel
View 1 more
- official Python wrapper (google-re2)
Limitations
- No backreferences or look-around assertions: RE2 leaves out constructs that only backtracking engines can implement12
- No Unicode normalization: patterns and text are matched by code point, so both must be normalized first if needed1
- No possessive quantifiers or atomic groups: the Syntax page marks them, and \Z and \G, as not supported2
Capabilities
| Has an API | plan not known |
|---|---|
| Has official SDKs | plan not known |
Alternatives
The same job
These do what RE2 does.
- re2 Safer regular expressions in Ruby
