javascript正则表达式,匹配没有组或积极的lookbehind

时间:2012-02-08 04:16:35

标签: javascript regex

我有一个大型的javascript数组,5000个左右的条目。为了以合理的性能方式对所有数组项运行RegExp匹配,我宁愿不循环exec并拔出组。我发现匹配没有将exec分组得更快*。

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

    // 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替代方案要么不起作用(逗号上的负面预测),要么引入额外的处理开销。

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题