For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/stage/unstaged/proposal-regexp-atomic-and-possessive.md.
  • 简体中文
  • RegExp Atomic Groups & Possessive Quantifiers ?

    中文标题:RegExp 原子组与占有量词

    提案概览
    提案速览

    该提案为 JavaScript 正则表达式引入原子组和占有量词,以防止灾难性回溯。原子组锁定其匹配并禁止回溯,而占有量词在标记匹配后阻止回溯。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    proposal-regexp-atomic-and-possessive

    一个向 RegExp 添加原子组和占有量词的提案。

    原子组

    原子组,用 (?>TEXT_TO_MATCH) 表示,一旦组匹配并“锁定”,就阻止回溯。即使回溯到一个备选分支可能允许整体匹配,原子组也不会解锁。

    const atomic = /a(?>bc|b)c/;
    
    // (?>bc) 匹配,因此原子组“锁定”。
    // 然后,组之后的 "c" 匹配。
    atomic.test('abcc'); // => true
    
    // (?>bc) 匹配,因此原子组“锁定”。
    // 表达式的其余部分不再匹配。
    // 因为原子组已锁定,它**不会**回溯
    // 到备选 (b) 分支。
    atomic.test('abc'); // => false
    
    // 原子组不捕获其匹配。
    atomic.exec('abcc'); // => ['abcc']

    占有量词

    占有量词,通过在量词后使用 + 表示,一旦标记匹配,就阻止回溯。即使回溯可能允许整体匹配,占有量词也不会允许。

    const possessive = /^(a|.b)++$/;
    
    // (a) 匹配
    possessive.test('a'); // => true
    // (a) 匹配,然后 (.b) 匹配
    possessive.test('abb'); // => true
    
    // (a) 匹配,(a) 匹配,但无法匹配 "b"
    // 因为它是占有的,它**不会**回溯
    // 到 (.b) 分支。
    possessive.test('aab'); // => false

    推进者

    状态

    当前阶段:0

    动机

    JavaScript 的正则表达式很棒,但开发者可能会无意中写出具有“灾难性回溯”的正则表达式。这些正则表达式可能完全冻结程序,对服务器尤其危险。

    原子组和占有量词允许开发者编写可理解的性能保证。由于它们不允许回溯,它们永远不会遭受指数级执行时间。

    const regex = /^(a|[ab])*$/;
    
    function test(length) {
      const str = 'a'.repeat(length) + 'c';
      const now = performance.now();
      regex.test(str);
      return performance.now() - now;
    }
    
    for (let i = 0; i < 50; i++) {
      console.log({ length: i, time: test(i) });
    }
    字符串长度时间(秒)
    ...剪断0.00
    190.01
    200.01
    210.03
    220.06
    230.11
    240.23
    250.44
    260.89
    271.79
    283.65
    297.32
    3014.29
    3128.45
    3257.94
    33114.02
    34233.58
    我厌倦了等待……

    相关