【问题标题】:Regex group optimization [duplicate]正则表达式组优化
【发布时间】:2022-01-21 20:09:04
【问题描述】:

在使用正则表达式匹配多个关键字的文档时,可能需要二次时间(文档数 × 关键字数)。

使用以下一组关键字:

['ant', 'antelope', 'albatross', 'alligator']

我会产生愚蠢的正则表达式:

/ant|antelope|albatross|alligator/

但我正在寻找一种将集合转换为类似内容的解决方案:

/a(nt(|elope)|l(batross|ligator))/

效率更高

【问题讨论】:

    标签: javascript node.js regex performance optimization


    【解决方案1】:

    我制作了一个简单的库,以便在 npm npm i regexp-factorize 上提供这项工作 可以如下使用

    import { factorizeOr } from 'regexp-factorize';
    
    const keywords = ['ant', 'antelope', 'albatross', 'alligator'];
    const regexpString = factorizeOr(keywords);
    const regexp = new RegExp(regexpString);
    
    const document = "There's an alligator in my house";
    
    console.log(regexp);                // /a(?:nt(?:|elope)|l(?:batross|ligator))/
    console.log(regexp.test(document)); // true
    

    【讨论】:

      猜你喜欢
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      相关资源
      最近更新 更多