← 中文资源

简体中文版本

RegExp 后行断言锚定前文

正向与负向后行断言以零宽方式锚定前文:键名前缀和 $ 符号不会混进捕获结果,match 拿到的就是纯值,还能反向排除不需要的前缀。

阅读英文原文

运行结果

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

ok codes: [ '200', '201' ]
error codes: [ '500', '503' ]
mentions: [ 'ada', 'grace' ]
email domain skipped: true
unprefixed: [ '89' ]

实现说明

各个操作都建立在顶层绑定之上:rows、okCodes、errorCodes、chat。

使用要点

  • 每一步打印都带着自己的标签:ok codes:、error codes:、mentions:。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件的状态由几个模块级绑定持有:rows、okCodes、errorCodes。

核心语句

const mentions = [...chat.matchAll(/(?<=\s)@(\w+)/g)].map((m) => m[1]);

代码示例

// Lookbehind assertions anchor a match to what came before, without
// including that context in the result.
const rows = 'ok:200 err:500 ok:201 err:503';

// Positive lookbehind: codes that directly follow "ok:"
const okCodes = rows.match(/(?<=ok:)\d{3}/g);
console.log('ok codes:', okCodes);

// Negative lookbehind: codes NOT directly preceded by "ok:"
const errorCodes = rows.match(/(?<!ok:)\d{3}/g);
console.log('error codes:', errorCodes);

// Mention extraction: @names preceded by whitespace, skipping email domains
const chat = 'Mentions: @ada @grace — email ada@example.com is not a mention';
const mentions = [...chat.matchAll(/(?<=\s)@(\w+)/g)].map((m) => m[1]);
console.log('mentions:', mentions);
console.log('email domain skipped:', !mentions.includes('example'));

// Negative lookbehind can exclude prices while keeping bare numbers
const tags = 'CPU $299 GPU $399 case 89';
console.log('unprefixed:', tags.match(/(?<!\$)\b\d+\b/g));