← 中文资源

简体中文版本

反向引用匹配重复词

模式里的 \1 会引用第一组捕获到的内容,于是 重复词、回显令牌 这类 事先不知道内容的重复 都能匹配;命名组用 \k<名字> 引用可读性更好。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

duplicate caught: the the
no repeat, no match: false
case matters: false
group 1: 7 full match: 7x7
named echo: gone

实现说明

演示用的数据放在这几个模块级绑定中:duplicate、doubled、match、echo。

使用要点

  • 演示输出是带标签的(duplicate caught:、no repeat, no match:、case matters:),每个操作都会留下自己的一行标注。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 跨调用保留的状态放在这些顶层绑定里:duplicate、doubled、match。

核心语句

const match = 'id=7x7'.match(doubled);

代码示例

// A backreference \1 inside the pattern recalls what group 1 captured,
// so repeated tokens match without knowing them in advance
const duplicate = /\b(\w+)\s+\1\b/;

console.log('duplicate caught:', 'the the same idea'.match(duplicate)[0]);
console.log('no repeat, no match:', duplicate.test('a single pass'));

// capture groups compare exactly: This this fails, This This would match
console.log('case matters:', duplicate.test('This this'));

// capture + backreference together rebuild the repeated token
const doubled = /(\d+)x\1/;
const match = 'id=7x7'.match(doubled);
console.log('group 1:', match[1], 'full match:', match[0]);

// named capture recalled with \k<name> reads better than a bare number
const echo = /(?<word>\w+) and \k<word>/;
console.log('named echo:', 'gone and gone'.match(echo).groups.word);