RE2's regular expression language is almost a superset of what RegExp provides
(see Syntax),
but it lacks backreferences and lookahead assertions. See below for details.
RE2 always works in Unicode mode — character codes are interpreted as Unicode code points, not as binary values of UTF-16.
See Unicode support for details.
RE2 emulates standard RegExp, making it a practical drop-in replacement in most cases.
It also provides String-based regular expression methods. The constructor accepts RegExp directly, honoring all properties.
It can work with binary data directly — Node.js Buffers, typed arrays, DataView, ArrayBuffer, SharedArrayBuffer — reducing overhead and making processing of long files fast.
The project is a C++ addon built with nan. It cannot be used in web browsers.
All documentation is in this README and in the wiki — browse the index, or search it by name.
Why use node-re2?
The built-in Node.js regular expression engine can run in exponential time with a special combination:
These methods are also available as well-known symbol-based methods for transparent use with ES6 string/regex machinery.
Buffer support
Most methods accept binary objects instead of strings for direct UTF-8 processing:
Buffer, any TypedArray (e.g., Uint8Array), DataView, ArrayBuffer, and SharedArrayBuffer
are all read as raw UTF-8 bytes (views at their byte offset and length):
re2.exec(buf)
re2.test(buf)
re2.match(buf)
re2.search(buf)
re2.split(buf[, limit])
re2.replace(buf, replacer)
Patterns, flags, and replace() replacement values can be binary objects too.
Differences from string-based versions:
All binary input is assumed to be encoded as UTF-8
(ASCII is a proper subset of UTF-8).
Results are Buffer objects for any binary input, even in composite objects. Convert with
buf.toString().
(Buffer is a Uint8Array subclass, so the results satisfy consumers expecting Uint8Array.)
All offsets and lengths are in bytes, not characters (each UTF-8 character occupies 1–4 bytes).
This lets you slice buffers directly without costly character-to-byte recalculations.
Writing to a SharedArrayBuffer concurrently while it is being matched yields unspecified
match results (reads are always kept in bounds).
When re2.replace() is used with a replacer function, the replacer receives string arguments and character offsets by default. Set useBuffers to true on the function to receive byte offsets instead:
This works for both string and buffer inputs. Buffer input produces buffer output; string input produces string output.
RE2.Set
Use RE2.Set when the same string must be tested against many patterns. It builds a single automaton and frequently beats running individual regular expressions one by one.
While test() can be simulated by combining patterns with |, match() returns which patterns matched — something a single regular expression cannot do.
new RE2.Set(patterns[, flagsOrOptions][, options])
patterns is any iterable of strings, binary objects (Buffer, TypedArray, DataView, ArrayBuffer, SharedArrayBuffer), RegExp, or RE2 instances; flags (if provided) apply to the whole set.
flagsOrOptions can be a string or binary object with standard flags (i, m, s, u, g, y, d).
options.anchor can be 'unanchored' (default), 'start', or 'both'.
options.maxMem is the DFA memory budget in bytes (positive integer). Default is 8 MiB — raise it to compile sets that would otherwise fail with "RE2.Set could not be compiled.".
set.test(str) returns true if any pattern matches and false otherwise.
set.match(str) returns an array of indexes of matching patterns.
This is an array of integer indices of patterns that matched sorted in ascending order.
If no patterns matched, an empty array is returned.
Read-only properties:
set.size (number of patterns), set.flags (RegExp flags as a string), set.anchor (anchor mode as a string)
set.source (all patterns joined with | as a string), set.sources (individual pattern sources as an array of strings)
set.maxMem (number) — effective DFA memory budget in bytes
RE2.unicodeWarningLevel — decide what happens when a non-Unicode regular expression is created.
How to install
npm install re2
The project works with other package managers but is not tested with them.
See the wiki for notes on yarn and pnpm.
Supported Node.js versions
re2 supports every non-EOL Node.js release — current and active LTS lines. As a native (nan) addon it runs on Node.js only, not Bun or Deno. The authoritative supported range is the engines field in package.json; it also pins the minimum patch releases the build toolchain (node-gyp 13) requires. Check engines for the exact floor rather than a version repeated here.
Install scripts (npm 12+)
re2 downloads or builds its native binary in an install script. Starting with npm 12
(July 2026), npm does not run dependency install scripts unless the package is listed in the
allowScripts field of your project's package.json — without it, npm install re2
fails with ESTRICTALLOWSCRIPTS. npm 11.16+ still runs the scripts but prints a warning.
Allow re2 before installing:
npm pkg set allowScripts.re2=true --jsonnpm install re2
Or use npm's approval tooling — note that npm approve-scripts only matches installed
packages, so under npm 12 the package has to be installed with scripts skipped first:
npm approve-scripts pins the approval to the installed version, so version updates ask again;
pass --no-allow-scripts-pin (or use the allowScripts.re2=true form above) to allow all
versions. No other package in re2's dependency tree runs install scripts. For the full story see
NPM 12 and install scripts
and GitHub's official announcement of the npm v12 breaking changes.
Precompiled artifacts
The install script attempts to download a prebuilt artifact from GitHub Releases. A download from GitHub is verified against the SHA-256 hashes pinned in this package's artifactHashes field before it is used — a binary that is not byte-for-byte the one published is rejected. Override the download location with the RE2_DOWNLOAD_MIRROR environment variable (a mirror serves your own builds and is not hash-checked). To skip the download entirely and always build from source, set RE2_DOWNLOAD_FORCE_BUILD to a non-empty value.
If the download fails or is rejected, the script builds RE2 locally using node-gyp.
Installing from git instead of npm (e.g. npm install uhop/node-re2#X.Y.Z; opt-in via --allow-git under npm 12) always builds from source: artifactHashes is stamped into package.json at publish time, so a checkout has no hashes for its own release's binaries and the download is rejected. The npm package is the verified artifact.
How to use
It is used just like RegExp.
const RE2 = require('re2');// with default flagslet re = new RE2('a(b*)');let result = re.exec('abbc');console.log(result[0]); // 'abb'console.log(result[1]); // 'bb'result = re.exec('aBbC');console.log(result[0]); // 'a'console.log(result[1]); // ''// with explicit flagsre = new RE2('a(b*)', 'i');result = re.exec('aBbC');console.log(result[0]); // 'aBb'console.log(result[1]); // 'Bb'// from regular expression objectconst regexp = new RegExp('a(b*)', 'i');re = new RE2(regexp);result = re.exec('aBbC');console.log(result[0]); // 'aBb'console.log(result[1]); // 'Bb'// from regular expression literalre = new RE2(/a(b*)/i);result = re.exec('aBbC');console.log(result[0]); // 'aBb'console.log(result[1]); // 'Bb'// from another RE2 objectconst rex = new RE2(re);result = rex.exec('aBbC');console.log(result[0]); // 'aBb'console.log(result[1]); // 'Bb'// shortcutresult = new RE2('ab*').exec('abba');// factoryresult = RE2('ab*').exec('abba');
Limitations (things RE2 does not support)
RE2 avoids any regular expression features that require worst-case exponential time to evaluate.
The most notable missing features are backreferences and lookahead assertions.
If your application uses them, you should continue to use RegExp —
but since they are fundamentally vulnerable to
ReDoS,
consider replacing them.
RE2 throws SyntaxError for unsupported features.
Wrap RE2 declarations in a try-catch to fall back to RegExp:
let re = /(a)+(b)*/;try { re = new RE2(re); // use RE2 as a drop-in replacement} catch (e) { // use the original RegExp}const result = re.exec(sample);
RE2 may also behave differently from the built-in engine in corner cases.
Backreferences
RE2 does not support backreferences — numbered references to previously
matched groups (\1, \2, etc.). Example:
RE2 does not support lookahead assertions, which make a match depend on subsequent contents.
/abc(?=def)/; // match abc only if it is followed by def/abc(?!def)/; // match abc only if it is not followed by def
Mismatched behavior
RE2 and the built-in engine may disagree in edge cases. Verify your regular expressions before switching. They should work in the vast majority of cases. For limits and differences you rarely meet, see Edge cases.
RE2 always works in Unicode mode. \p{...} and \P{...} accept the same property escapes as the built-in RegExp with the u flag, except Properties of Strings. For details, see Unicode support.
Release history
1.27.1 Two DoS security fixes: split() on a zero-width match no longer takes quadratic time (GHSA-7gf8-v4c4-pph7), and an amplifying replace() template throws a RangeError before allocating its result (GHSA-x77q-8rq8-rq6v). \B no longer matches inside a multi-byte character. Thx, AmirWilayah (ADGepuk Research).
1.27.0 Binary input beyond Buffer: typed arrays, DataView, ArrayBuffer, and SharedArrayBuffer (#233). Passing a non-RE2 native object to the constructor throws a TypeError instead of crashing (thx, theosotr).
1.26.1 Security fix (GHSA-j4r3-hg7j-8chg): a Buffer subject, pattern, or replacement ending in a truncated multi-byte UTF-8 character no longer reads past the end of the buffer — for replace() and split() those stray bytes were copied into the returned Buffer. Buffer input only; strings were never affected. Thx, Ovo.
1.25.2 Two DoS security fixes: a global match() with an empty-matchable pattern (a*, (?:), …) no longer loops forever exhausting memory (GHSA-6hxr-mr5r-9836), and an out-of-range lastIndex on a non-ASCII subject no longer reads past the buffer and crashes (GHSA-ff84-5f28-78qj). Both now match the built-in engine. Thx, ataberk-xyz.
1.25.1 Security fix (GHSA-8hcv-x26h-mcgp): a global replace() using an output-amplifying template ($' or $`) on very large input could exceed V8's maximum string length and abort the whole process. It now throws a catchable RangeError, matching the built-in engine. Thx, ataberk-xyz.
1.25.0 Full Unicode 17.0.0 property classes (Fixes #226). New maxMem option for RE2.Set. Faster matching on pure-ASCII inputs. Narrowed Node support — drops Node 25.x and older patch releases.
1.24.1 Support for Node 22, 24, 26 + precompiled binaries.
1.24.0 Fixed multi-threaded crash in worker threads (#235). Added named import: import {RE2} from 're2'. Added CJS test. Updated docs and dependencies.
1.23.3 Updated Abseil and dev dependencies.
1.23.2 Updated dev dependencies.
1.23.1 Updated Abseil and dev dependencies.
1.23.0 Updated all dependencies, upgraded tooling. New feature: RE2.Set (thx, Wes).
1.22.3 Technical release: upgraded QEMU emulations to native ARM runners to speed up the build process.
1.22.2 Updated all dependencies and the list of pre-compiled targets: Node 20, 22, 24, 25 (thx, Jiayu Liu).
1.22.1 Added support for translation of scripts as Unicode classes.
1.21.5 Updated all dependencies and the list of pre-compiled targets. Fixed minor bugs. C++ style fix (thx, Benjamin Brienen). Added Windows 11 ARM build runner (thx, Kagami Sascha Rosylight).
1.21.4 Fixed a regression reported by caroline-matsec, thx! Added pre-compilation targets for Alpine Linux on ARM. Updated deps.
1.21.3 Fixed an empty string regression reported by Rhys Arkins, thx! Updated deps.
1.21.2 Fixed another memory regression reported by matthewvalentine, thx! Updated deps. Added more tests and benchmarks.
1.21.1 Fixed a memory regression reported by matthewvalentine, thx! Updated deps.
1.21.0 Fixed the performance problem reported by matthewvalentine (thx!). The change improves performance for multiple use cases.
1.20.12 Updated deps. Maintenance chores. Fixes for buffer-related bugs: exec() index (reported by matthewvalentine, thx) and match() index.
1.20.11 Updated deps. Added support for Node 22 (thx, Elton Leong).
1.20.10 Updated deps. Removed files the pack used for development (thx, Haruaki OTAKE). Added arm64 Linux prebilds (thx, Christopher M). Fixed non-npmcorepack problem (thx, Steven).
1.20.9 Updated deps. Added more absail-cpp files that manifested itself on NixOS. Thx, Laura Hausmann.
1.20.8 Updated deps: install-artifact-from-github. A default HTTPS agent is used for fetching precompiled artifacts avoiding unnecessary long wait times.
1.20.7 Added more absail-cpp files that manifested itself on ARM Alpine. Thx, Laura Hausmann.
1.20.6 Updated deps, notably node-gyp.
1.20.5 Updated deps, added Node 21 and retired Node 16 as pre-compilation targets.
1.20.4 Updated deps. Fix: the 2nd argument of the constructor overrides flags. Thx, gost-serb.
1.20.3 Fix: subsequent numbers are incorporated into group if they would form a legal group reference. Thx, Oleksii Vasyliev.
1.20.2 Fix: added a missing C++ file, which caused a bug on Alpine Linux. Thx, rbitanga-manticore.
1.20.1 Fix: files included in the npm package to build the C++ code.
1.20.0 Updated RE2. New version uses abseil-cpp and required the adaptation work. Thx, Stefano Rivera.
The rest can be consulted in the project's wiki Release history.