实现说明
演示用的数据放在这几个模块级绑定中: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);