JavaScript RegExp.lastIndex:为什么重复 test 与 exec 会得到不同结果
同一段文字,第一次 test 返回 true,第二次却变成 false?先别急着修改匹配规则。带 g 或 y 的正则对象会保存 lastIndex,下一次调用接着使用这个状态。本文用十二组可运行断言拆开这些行为,讨论普通内建正则,不涉及改写 exec、Symbol.matchAll 或子类构造器的情况。
配图:独立模型生成的概念示意图,不是程序运行截图。
一、先分清从哪里找
g 表示全局搜索:从 lastIndex 对应的位置开始尝试,当前位置不匹配时可以继续向后找。y 表示粘连匹配:必须在该位置成功,不能跳过前面的字符。二者都存在时,exec 与 test 仍遵守粘连限制。这里的“全局”不会让一次 exec 自动返回所有结果,每次成功仍只返回一次匹配。
成功后,两类正则把 lastIndex 写为匹配结束位置;找不到匹配,或起点已经超过字符串长度,就归零。注意“写为结束位置”不等于“一定向前移动”。没有 g、也没有 y 时,普通匹配从头搜索,不把预设的 lastIndex 当作起点,也不因成功或失败改写它。依据:TC39 内建匹配算法。
二、布尔返回值也可能改变状态
test 并不是只读查询。它通过匹配结果判断真假,因此与同一对象的 exec 共用游标。先 test 再 exec,后者可能已经跳过第一处命中。更容易漏掉的是跨字符串复用:先检测一段文本,再传入另一段文本,不会自动清零。脚本第八组用两段不同输入复现这种遗漏,随后验证失败会复位。参考:MDN test。
三、字符位置与空匹配是两件事
lastIndex 采用 UTF-16 码元偏移,不是视觉字符数量。一个补充平面的表情占两个码元;启用 u 后,点号能一次匹配整个表情,但结束偏移仍是二。不要把这个数直接当作用户眼中的“第几个字”,组合字符和字形簇也不是本文处理的范围。
零长度 exec 成功后可以停留在原位置,第十组只执行三次,安全展示重复结果,没有依赖失败退出的无限循环。若业务允许空匹配,不能盲目使用普通 exec 循环;手动推进必须考虑 Unicode 语义,或者选择下节的迭代接口。参考:MDN lastIndex、MDN exec。
四、让一次操作拥有自己的正则
对普通正则,字符串的 matchAll 要求 g,并建立独立匹配副本;副本继承调用时的 lastIndex,不保证从零开始,遍历不会推进原对象。它还会处理空匹配的推进,第十一组验证表情两端的空匹配位置。参考:MDN matchAll。
只判断是否包含模式时,通常不需要 g 或 y;确实要逐项扫描时,让正则属于本次操作,不要把带游标的对象藏在共享模块变量中。主动归零只适合你明确拥有该对象的场景,随手重置调用方传来的对象可能破坏它正在进行的扫描。这些做法解决状态管理,不代表模式能校验所有输入,也不是性能或安全保证。
五、完整验证脚本
保存为 test_regexp_state.cjs,分别运行 node test_regexp_state.cjs 与 node --use-strict test_regexp_state.cjs。本文在 Node v24.19.0 实测两种方式均通过十二组断言;末行应为 PASS: 12 deterministic groups。
const assert = require('node:assert/strict');
let passed = 0;
function group(name, run) {
run();
passed += 1;
console.log(`ok ${passed} - ${name}`);
}
group('plain regex ignores the cursor', () => {
const re = /a/;
re.lastIndex = 42;
assert.equal(re.exec('ba').index, 1);
assert.equal(re.lastIndex, 42);
assert.equal(re.test('z'), false);
assert.equal(re.lastIndex, 42);
});
group('global test remembers its state', () => {
const re = /a/g;
const seen = Array.from({ length: 3 }, () => [re.test('a'), re.lastIndex]);
assert.deepEqual(seen, [[true, 1], [false, 0], [true, 1]]);
});
group('global exec may search later positions', () => {
const re = /a/g;
const text = 'ba--a';
assert.equal(re.exec(text).index, 1);
assert.equal(re.lastIndex, 2);
assert.equal(re.exec(text).index, 4);
assert.equal(re.lastIndex, 5);
});
group('global failure and out of range reset', () => {
const re = /a/g;
re.lastIndex = 1;
assert.equal(re.exec('a'), null);
assert.equal(re.lastIndex, 0);
re.lastIndex = 9;
assert.equal(re.exec('a'), null);
assert.equal(re.lastIndex, 0);
});
group('sticky requires exactly the cursor position', () => {
const re = /a/y;
assert.equal(re.exec('ba'), null);
assert.equal(re.lastIndex, 0);
re.lastIndex = 1;
assert.equal(re.exec('ba').index, 1);
assert.equal(re.lastIndex, 2);
assert.equal(re.exec('ba'), null);
assert.equal(re.lastIndex, 0);
});
group('g does not cancel sticky behavior', () => {
const re = /a/gy;
assert.equal(re.test('ba'), false);
re.lastIndex = 1;
assert.equal(re.test('ba'), true);
assert.equal(re.lastIndex, 2);
});
group('test and exec share one regex cursor', () => {
const re = /a/g;
assert.equal(re.test('aba'), true);
assert.equal(re.lastIndex, 1);
assert.equal(re.exec('aba').index, 2);
assert.equal(re.lastIndex, 3);
});
group('a different string does not reset state', () => {
const re = /a/g;
assert.equal(re.test('a'), true);
assert.equal(re.lastIndex, 1);
assert.equal(re.test('ab'), false);
assert.equal(re.lastIndex, 0);
assert.equal(re.test('ab'), true);
});
group('Unicode matching still reports UTF-16 offsets', () => {
const text = '\u{1F600}a';
const re = /./gu;
assert.equal(text.length, 3);
assert.equal(re.exec(text)[0], '\u{1F600}');
assert.equal(re.lastIndex, 2);
assert.equal(re.exec(text).index, 2);
assert.equal(re.lastIndex, 3);
const codeUnit = /./g;
assert.equal(codeUnit.exec(text)[0].length, 1);
assert.equal(codeUnit.lastIndex, 1);
});
group('zero-length exec stays put in a bounded demo', () => {
const re = /(?=a)/g;
const seen = [];
for (let step = 0; step < 3; step += 1) {
const match = re.exec('a');
seen.push([match.index, match[0].length, re.lastIndex]);
}
assert.deepEqual(seen, [[0, 0, 0], [0, 0, 0], [0, 0, 0]]);
});
group('matchAll clones state and advances empty matches', () => {
const re = /a/g;
re.lastIndex = 1;
assert.deepEqual([...('aba'.matchAll(re))].map(m => m.index), [2]);
assert.equal(re.lastIndex, 1);
const iterator = 'aba'.matchAll(re);
re.lastIndex = 0;
assert.deepEqual([...iterator].map(m => m.index), [2]);
assert.equal(re.lastIndex, 0);
assert.throws(() => 'aba'.matchAll(/a/), TypeError);
const empty = /(?:)/gu;
assert.deepEqual([...('\u{1F600}'.matchAll(empty))].map(m => m.index), [0, 2]);
assert.equal(empty.lastIndex, 0);
});
group('each operation owns its regex state', () => {
function containsA(text) {
return /a/.test(text);
}
function aPositions(text) {
const re = /a/g;
return [...text.matchAll(re)].map(m => m.index);
}
assert.deepEqual(['a', 'ab', 'z'].map(containsA), [true, true, false]);
assert.deepEqual(aPositions('aba'), [0, 2]);
assert.deepEqual(aPositions('a'), [0]);
});
assert.equal(passed, 12);
console.log('PASS: 12 deterministic groups'); 

