Library / SDK
google/re2 avatar
google/re2

RE2: Google's C++ regex library with a linear-time safety guarantee

RE2 is a fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python. It is a C++ library.

9,817 stars1,256 forksC++BSD-3-Clause

At a glance

What is it?
RE2 is a C++ regular expression library that guarantees match time linear in the input length regardless of the pattern. It is the practical choice for services that evaluate patterns from untrusted users, but it gives up backreferences and look-around assertions to keep that guarantee.
Who is it for?
RE2 is the correct choice when regular expressions come from untrusted input and the linear-time guarantee matters more than feature breadth. It is the wrong choice for patterns that require backreferences or look-around assertions: those will fail to compile with no option to override the restriction.
Can I use it commercially?
Yes. BSD-3-Clause is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 9 days ago.
What is it written in?
Mainly C++, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on October 11, 2026, and from our analysis. They are not legal advice.

Editorial analysis

A C++ regex library in production at Google since 2006, with linear time as its primary guarantee

RE2 is a C++ regular expression library that has been used in production at Google and elsewhere since 2006. Its primary design goal is not speed but safety: the match time is guaranteed to be linear in the length of the input string, regardless of the pattern.

The risk in backtracking engines such as PCRE, Perl, and Python's `re` module is that certain patterns on certain inputs trigger exponential backtracking. A carefully crafted pattern submitted by a malicious user can bring a server to a halt, and RE2 eliminates that class of attack by construction: any pattern RE2 accepts runs in linear time.

Beyond the time guarantee, RE2 limits memory usage through a configurable budget. The parser, the compiler, and the execution engines all honor that budget and fail gracefully when it is exhausted. Stack overflow is prevented by refusing to use recursion internally. For services that accept regular expressions from untrusted users, these 3 properties (linear time, bounded memory, no stack overflow) are the core of the safety argument.

How RE2 evaluates all alternatives in parallel rather than testing them sequentially

A backtracking engine tests each alternative in a pattern sequentially, stopping at the first successful match. That behavior makes backtracking engines fast when the first alternative is the common case. The penalty appears when no alternative matches: the engine backtracks and retries, potentially with exponentially deep recursion on adversarial inputs.

RE2 evaluates all alternatives in parallel using an NFA-to-DFA simulation, where a backtracking engine is optimistic (expecting early success), while RE2 is pessimistic: it commits no more work than necessary but evaluates every path simultaneously. The trade-off is a constant-factor overhead for patterns where the first alternative matches most inputs. For complex patterns or adversarial inputs, RE2's approach has a bounded worst case where backtracking does not.

RE2 operates in 2 distinct modes: Perl mode (the default), which accepts most Perl operators, and POSIX mode, which accepts standard POSIX egrep syntax and returns the leftmost-longest match rather than the match that Perl would have chosen. Both modes share the same linear-time execution guarantee.

What RE2 refuses to support: backreferences and look-around assertions

RE2 operates on a principled exclusion: it does not support any construct for which only a backtracking solution is known to exist. Backreferences and generalized look-around assertions both fall into that category. They are not configurable, and no option re-enables them. A pattern that uses a backreference to refer to a previously captured group will fail to compile, not run slowly.

Submatching, meaning capture groups, is still fully supported. A pattern like `(\\w+):(\\d+)` compiles and executes correctly. The exclusion applies specifically to referencing a previously captured group later in the same pattern, or to assertions that require the engine to look backward or forward without consuming any input.

For engineers who already rely on backreferences or generalized assertions in their patterns, RE2 is the wrong tool and there is no way to configure it otherwise. The supported syntax for Perl mode is documented in detail on the project's Syntax wiki page. Auditing existing patterns against that page should be the first step before committing to RE2 in any production system.

Installing RE2: 3 build systems and their platform-specific dependencies

RE2 supports 3 build systems: GNU make, CMake, and Bazel. The simplest path uses make:

bash
make
make test
make benchmark
make install
make testinstall

Building RE2 requires a C++17 compiler and the Abseil library. The tests and benchmarks add GoogleTest and Benchmark as additional dependencies. Platform-specific installation commands for those dependencies:

- Linux: `apt install libabsl-dev libgtest-dev libbenchmark-dev` - macOS: `brew install abseil googletest google-benchmark pkg-config-wrapper` - Windows: `vcpkg install abseil gtest benchmark`

The Abseil dependency is the most significant cost for projects that do not already use it. Abseil is Google's C++ base library, and pulling it in for RE2 alone means adding a large collection of utilities. Projects already on the Abseil stack pay no extra dependency cost.

Optional ICU support for full Unicode property matching is available but commented out by default in the Makefile. Enabling it requires ICU to be installed and 2 additional lines in the Makefile to be uncommented.

The C++ matching API: FullMatch, PartialMatch, and submatch extraction into typed arguments

RE2 exposes 2 primary matching functions. `RE2::FullMatch` requires the regular expression to match the entire input string. `RE2::PartialMatch` searches for a match anywhere in the input, returning the leftmost-longest match in POSIX mode or the Perl-mode match otherwise.

Both functions accept additional arguments into which captured subgroups are extracted. The argument type determines how the captured text is parsed: a `string*` receives the raw matched text, an integer type (passed by pointer) parses the capture as a number, and `absl::string_view*` provides a zero-copy view into the original input string. A submatch extraction example:

cpp
int i;
string s;
assert(RE2::FullMatch("ruby:1234", "(\\w+):(\\d+)", &s, &i));
assert(s == "ruby");
assert(i == 1234);

For repeated matching with the same pattern, compiling once into an RE2 object and reusing it avoids recompilation overhead on every call. Running `re.ok()` checks whether compilation succeeded. Compilation errors can be suppressed by passing `RE2::Quiet` as the second constructor argument, after which `re.error()` carries the failure text instead of printing to stderr.

Integer overflow in submatch extraction silently returns false, indistinguishable from a non-match

A specific behavior visible in the API examples but not explained in the prose: when a captured group parses to an integer that would overflow the target type, `FullMatch` returns false rather than storing an incorrect value or setting a separate error state.

The example from the documentation: `assert(!RE2::FullMatch("ruby:123456789123", "(\\w+):(\\d+)", &s, &i))` with the comment "Fails: integer overflow keeps value from being stored in i." The pattern matches the input string, but the submatch extraction fails because 123456789123 cannot be stored in a standard integer, and the return value false is identical to what a genuine non-match produces.

There is no separate error signal. A caller cannot distinguish a non-match from an overflow failure without removing the integer argument and re-calling with only string extraction. For patterns that extract user-supplied numeric values, choosing an integer type with adequate range (or extracting as a string first and parsing separately) eliminates this ambiguity. The practical consequence: range checking belongs upstream of the RE2 call when integer extraction is in use.

The absl::string_view dependency, Unicode code points, and available options

RE2 uses `absl::string_view` rather than `std::string_view` in its submatch extraction API. This is by design for historical reasons: RE2 predates the standardization of `std::string_view` in C++17, and the API commitment to the Abseil type has not changed. Any project using RE2 submatch extraction into views must use the Abseil type rather than the standard one, even when targeting C++17 or later compilers.

RE2 operates on Unicode code points. It makes no attempt at normalization: the pattern /ü/ (U+00FC, u with precomposed diaeresis) does not match the same character represented as U+0075 followed by combining U+0308. Normalization is described as a long, involved topic. For applications that need such matches, normalizing both patterns and inputs before calling RE2 is the documented approach.

3 predefined option values cover common variations. `Latin1` disables UTF-8 mode for byte-level matching. `POSIX` enables POSIX syntax and leftmost-longest semantics. `RE2::Quiet` silences compilation errors to stderr. Additional options are available by constructing a `RE2::Options` object and configuring its fields directly before passing it to the RE2 constructor.

Abseil adoption cost, BSD-3-Clause terms, and when PCRE is the right choice

RE2 uses date-format version tags. 3 have been published in the past year: 2025-11-05, 2025-08-12, and 2025-08-05. The last push was on 2026-10-02. BSD-3-Clause terms permit commercial use and redistribution with attribution.

PCRE (and its successor PCRE2) supports backreferences, generalized look-around assertions, and a broader set of Perl-compatible features. For projects that need those features and control who writes the patterns, PCRE is the appropriate choice. When users submit patterns, a backreference-capable engine exposes the service to exponential-time inputs. RE2 trades feature breadth for a hard safety boundary that holds regardless of pattern complexity.

The Abseil dependency and the C++17 requirement are the 2 main adoption costs. Projects that do not currently use Abseil add a substantial base library to their build. The 3 supported build systems (make, CMake, Bazel) cover common C++ project configurations, but dependency management for Abseil requires explicit handling regardless of which build system is chosen.

Editorial conclusion

RE2 is the correct choice when regular expressions come from untrusted input and the linear-time guarantee matters more than feature breadth. It is the wrong choice for patterns that require backreferences or look-around assertions: those will fail to compile with no option to override the restriction. Before adopting RE2, verify that existing patterns compile under it, and check that any submatch extraction into integer types uses a type with adequate range, because overflow returns false with no signal separate from a genuine non-match.

Frequently asked questions

What makes RE2 safe for user-supplied regular expressions?

RE2 guarantees that match time is linear in the length of the input string, regardless of the pattern. This means a user-supplied pattern cannot cause exponential backtracking or a denial-of-service condition, regardless of what the pattern contains.

Does RE2 support backreferences?

No. RE2 excludes backreferences and look-around assertions because implementing them requires a backtracking approach, which would break the linear-time guarantee. Capture groups are supported; referencing a captured group later in the same pattern is not.

What does building RE2 require?

A C++17 compiler and the Abseil library are required to build RE2. Running the tests and benchmarks also requires GoogleTest and Benchmark. On Linux, these can be installed with `apt install libabsl-dev libgtest-dev libbenchmark-dev`.

Why does RE2::FullMatch return false when a captured integer overflows?

RE2 returns false from FullMatch when any submatch extraction fails, including when a captured group parses to a value that overflows the integer type of the argument. The return value is the same as for a genuine non-match, so the caller cannot distinguish the two cases without re-running without the integer argument.

What is the difference between RE2::FullMatch and RE2::PartialMatch?

RE2::FullMatch requires the regular expression to match the entire input string and returns false if any part of the input is left unmatched. RE2::PartialMatch searches for a match anywhere within the input string, returning the leftmost-longest match in POSIX mode or the Perl-mode match in the default Perl mode.

Official sources

  1. google/re2 on GitHub
  2. Issues
  3. License: BSD-3-Clause
  4. README
  5. Releases
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/google-re2.svg)](https://hysenlabs.com/projects/google-re2)