在Javascript循环内运行exec()

时间:2019-03-04 04:46:00

标签: javascript node.js regex

我不确定这似乎是什么问题,但是在Javascript(Nodejs,Chrome控制台,Firefox控制台)的for循环中运行exec()会产生错误的结果。据我所知,exec()是一个同步方法,在同步循环内部调用,应产生预期的输出。

const FILTER_REGEX = /(\w+)\s+(below|under|lesser than|lower than|above|over|more than|higher than|greater than|equals|equal to|same as|>|<|=)\s+(\d+)/gi;
const searchQuery = "Package Quantity > 50000 Date yearly ListPrice above 100";
const filterMatches = searchQuery.match(FILTER_REGEX) || [];
for(const filterMatch of filterMatches) {
    const filterMatchGroups = FILTER_REGEX.exec(filterMatch);
    console.log(`filterMatch: ${filterMatch}, filterMatchGroups: ${filterMatchGroups}`);
}

当前,我得到以下内容作为输出,有时第一个字符串的filterMatchGroups变为空,并为第二个字符串提供filterMatchGroups。

filterMatch: Quantity > 50000, filterMatchGroups: Quantity > 50000,Quantity,>,50000
filterMatch: ListPrice above 100, filterMatchGroups: null

1 个答案:

答案 0 :(得分:0)

这应该做到。

const FILTER_REGEX = /(\w+)\s+(below|under|lesser than|lower than|above|over|more than|higher than|greater than|equals|equal to|same as|>|<|=)\s+(\d+)/gi;
const searchQuery = "Package Quantity > 50000 Date yearly ListPrice above 100";
const filterMatches = searchQuery.match(FILTER_REGEX) || [];
for(const filterMatch of filterMatches) {
    FILTER_REGEX.lastIndex = 0;
    const filterMatchGroups = FILTER_REGEX.exec(filterMatch);
    console.log(`filterMatch: ${filterMatch}, filterMatchGroups: ${filterMatchGroups}`);
}

唯一可见的区别是 FILTER_REGEX.lastIndex = 0 ,如果必须再次使用它,则必须重置Regex的lastIndex属性,否则它将从先前存储的lastIndex开始进行正则表达式检查。感谢@CertainPerfomance @Andreas提供的链接和说明。

参考:Detailed Explanation