@adguard/re2-wasm

中文文档
1.2.1发布于 2026/07/14Apache-2.0TypeScriptCommonJS零依赖近 30 天下载 1.4万

Google's RE2 library distributed as a WASM module patched by AdGuard.

原始使用文档
文档目录24 节
  1. Description
  2. Table of Contents
  3. Installation
  4. Quick Start
  5. API Overview
  6. Constructor
  7. Properties
  8. Methods
  9. Usage Examples
  10. Constructing from a RegExp object
  11. Using the maxMem option to bound memory
  12. Named capture groups
  13. Using Symbol.matchAll
  14. Replacing with a function
  15. Falling back to RegExp for unsupported patterns
  16. Differences from RegExp
  17. Backreferences and lookahead assertions not supported
  18. Unicode flag is mandatory
  19. Memory limit
  20. Dot behavior
  21. Anchors in multiline mode
  22. compile() method
  23. d flag (hasIndices)
  24. Documentation

@adguard/re2-wasm NPM version

Google's RE2 library distributed as a WASM module patched by AdGuard.

Note: This package is developed in AdGuardSoftwareLimited/ext-re2-wasm. The AdguardTeam/re2-wasm repository is a public mirror.

Description

@adguard/re2-wasm is a fork of Google's re2-wasm that adds a configurable maximum memory limit for regular expressions. It compiles Google's RE2 C++ library to WASM via Emscripten and exposes it as a drop-in replacement for JavaScript's RegExp.

This library is for JavaScript and TypeScript developers who need to handle user-supplied regular expressions safely. The built-in RegExp engine can run in exponential time with a vulnerable regular expression and "evil input", leading to Regular Expression Denial of Service (ReDoS). RE2 guarantees linear-time matching, protecting your application from ReDoS attacks. The AdGuard fork adds bounded memory usage via the maxMem option — the engine throws an error if a match attempt exceeds the configured memory limit, preventing runaway resource consumption.

RE2's regular expression language is almost a superset of what is provided by RegExp (see Syntax), but it lacks two features: backreferences and lookahead assertions. See Differences from RegExp for details.

Table of Contents


Installation

npm install @adguard/re2-wasm

Requires Node.js ≥ 10 or a browser with WASM support. The package has zero runtime dependencies — all functionality comes from the compiled WASM module.

Quick Start

const { RE2 } = require('@adguard/re2-wasm');

const re = new RE2('hello (\\w+)', 'u');
const result = re.exec('hello world');
// result[0]: 'hello world'
// result[1]: 'world'
// result.index: 0
console.log(result[0]); // 'hello world'

Or with ES modules:

import { RE2 } from '@adguard/re2-wasm';

const re = new RE2('\\d+', 'gu');
'abc 123 def 456'.match(re); // ['123', '456']

API Overview

The RE2 class emulates the standard RegExp interface. It can be used as a drop-in replacement in most cases.

Constructor

new RE2(pattern: string | RegExp | RE2, flags?: string, maxMem?: number)
ParameterTypeDescription
patternstring, RegExp, or RE2The regular expression pattern. Accepts existing RegExp or RE2 objects.
flagsstringStandard RegExp flags (g, i, m, s, u, y). The u flag is required.
maxMemnumberMaximum memory in bytes the regex engine can use. Defaults to 0 (no limit). If exceeded, throws an error.

Properties

PropertyTypeDescription
lastIndexnumberIndex at which to start the next match (used with g and y flags).
globalbooleanWhether the g flag is set.
ignoreCasebooleanWhether the i flag is set.
multilinebooleanWhether the m flag is set.
dotAllbooleanWhether the s flag is set.
unicodebooleanWhether the u flag is set. Always true.
stickybooleanWhether the y flag is set.
sourcestringThe original pattern string.
flagsstringThe flags string.
internalSourcestringThe pattern after translation to RE2 syntax (read-only, for debugging).

Methods

MethodDescription
exec(str: string): RE2ExecArray | nullExecutes a search for a match. Returns a match array or null.
test(str: string): booleanTests for a match. Returns true or false.
toString(): stringReturns the regex as a string (/pattern/flags).
match(str: string): RE2MatchArray | nullMatches the string against the regex. Equivalent to String.prototype.match.
search(str: string): numberSearches for a match. Equivalent to String.prototype.search.
replace(str: string, replacer: string | function): stringReplaces matches. Equivalent to String.prototype.replace.
split(str: string, limit?: number): (string | undefined)[]Splits the string. Equivalent to String.prototype.split.

The RE2 class also supports well-known symbols, so String methods work directly:

const re = new RE2('\\d+', 'u');
'abc 123'.match(re);        // ['123', index: 4, input: 'abc 123']
'abc 123'.search(re);       // 4
'abc 123'.replace(re, 'X'); // 'abc X'
'abc 123'.split(re);        // ['abc ', '']

Usage Examples

Constructing from a RegExp object

const orig = /\w+/gu;
const re = new RE2(orig);
// Flags and pattern are copied from the original
console.log(re.flags); // 'gu'

Using the maxMem option to bound memory

// Limit the regex engine to 4 KB of memory
const re = new RE2('a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*', 'u', 4096);
try {
  re.exec('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
} catch (e) {
  console.log('Pattern exceeded memory limit');
}

Named capture groups

const re = new RE2('(?P<word>\\w+) (?P<number>\\d+)', 'u');
const result = re.exec('hello 42');
console.log(result.groups.word);   // 'hello'
console.log(result.groups.number); // '42'

Using Symbol.matchAll

const re = new RE2('\\w+', 'gu');
for (const match of 'one two three'.matchAll(re)) {
  console.log(match[0]);
}
// 'one'
// 'two'
// 'three'

Replacing with a function

const re = new RE2('(\\d+)', 'gu');
const result = re.replace('a 10 b 20 c 30', (match, n) => String(Number(n) * 2));
console.log(result); // 'a 20 b 40 c 60'

Falling back to RegExp for unsupported patterns

const pattern = /(a)+(b)*\\1/u;
let re;
try {
  re = new RE2(pattern);
} catch (e) {
  // Pattern uses backreferences — fall back to RegExp
  re = pattern;
}
const result = re.exec('aabbaabb');

Differences from RegExp

Backreferences and lookahead assertions not supported

RE2 does not support backreferences (\\1, \\2, etc.) or lookahead/lookbehind assertions ((?=...), (?<=...), (?!...), (?<!...)). Attempting to use these features throws a SyntaxError. If your patterns require them, fall back to RegExp (see the fallback example above).

Unicode flag is mandatory

The RE2 engine always works in Unicode mode. The u flag must be passed when constructing an RE2 instance:

new RE2('\\w+');           // throws Error: "u" flag must be passed
new RE2('\\w+', 'u');      // OK

Memory limit

The maxMem constructor parameter (an AdGuard extension) restricts how much memory the regex engine can allocate during matching. If the limit is exceeded, the engine throws an error. Pass 0 (the default) for no limit.

Dot behavior

In RE2, . matches any character including \\n, regardless of whether the m or s flags are set. This is equivalent to RegExp's s (dotAll) flag always being on:

const re = new RE2('a.b', 'u');
console.log(re.exec('a\\nb')); // ['a\\nb']
console.log(/a.b/u.exec('a\\nb')); // null

Anchors in multiline mode

In multiline mode, $ in RE2 does not match between \\r and \\n when the string ends with \\r\\n:

const re = new RE2('a$', 'mu');
re.exec('a\\r\\n'); // null — RE2 does not match between \\r and \\n
/a$/mu.exec('a\\r\\n'); // ['a'] — RegExp matches between \\r and \\n

compile() method

RegExp.prototype.compile() is deprecated and not implemented in RE2. Calling it throws an error. Create a new RE2 instance instead.

d flag (hasIndices)

The hasIndices (d) flag is not supported. Use RegExp with the d flag if you need start and end indices of capture groups.


Documentation

版本与发布记录

@adguard/re2-wasm 共发布 2 个版本,首次发布于 2024/06/19;过去 12 个月发布了 1 个版本。

版本发布日期距今
1.2.1latest2026/07/143 个月前
1.2.02024/06/192 年前

关于 @adguard/re2-wasm 的常见问题

@adguard/re2-wasm 是什么?

Google's RE2 library distributed as a WASM module patched by AdGuard.

如何安装 @adguard/re2-wasm?

在项目目录运行 npm install @adguard/re2-wasm,或使用 pnpm add / yarn add / bun add。

@adguard/re2-wasm 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adguard/re2-wasm 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@adguard/re2-wasm 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=10。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adguard/re2-wasm 可以商用吗?

@adguard/re2-wasm 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@adguard/re2-wasm 的下载量有多少?

根据 npm 官方下载统计,@adguard/re2-wasm 在 2026/10/05 – 2026/11/03 这 30 天内被下载 14,022 次,日均约 467 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adguard/re2-wasm 还在维护吗?

最新版本 1.2.1 发布于 2026/07/14(3 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 1 个;首次发布于 2024/06/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。