【问题标题】:javascript regex, matching without groups or positive lookbehindjavascript 正则表达式,无组匹配或正向后视
【发布时间】:2012-02-08 12:23:11
【问题描述】:

我有一个大型 javascript 数组,大约有 5000 个条目。为了以合理的性能方式对所有数组项运行 RegExp 匹配,我不希望循环 exec 并拉出组。我发现不分组 exec 的匹配要快得多*。

鉴于 javascript 没有积极的后向操作,是否可以使用标准正则表达式工具包获取以下值并仅匹配数字而不会出现误报?

    // the value to be matched
    var reference_field = ',1,3,8,123,';
    // a series of reference id to match
    var re = /(?:3|8)(?=,)/g;
    reference_field.match(re);
    // result, note that the second three was not intended --> ["3", "8", "3"]

如果数组不是那么长,我只是将数字分组,例如

    // the value to be matched
    var reference_field = ',1,3,8,123,';
    // a series of reference id to match
    var re = /,(3|8)(?=,)/g;
    var match;
    while(match = re.exec(reference_field)){
        if (match == null) {break;}
        // do something with match[1]
    }

...但就目前而言,我对速度很敏感,因为移动设备是一个目标平台。我是否错过了一个正则表达式技巧,或者没有分组就不可能。所有 javascript 正向lookbehind 替代方案要么不起作用(逗号上的负向lookahead),要么引入额外的处理开销。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    \b 序列可以为您工作——它匹配单词边界,包括单词的开头和结尾。如果您知道您的字符串始终是这些逗号分隔的数字列表,那么这将找到适当的匹配项:

    /\b(?:3|8)\b/g
    

    reference_field 的开头和结尾也不需要额外的逗号。

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 2011-11-29
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多