在Javascript中的循环中运行exec()

在Javascript中的循环中运行exec(),javascript,node.js,regex,Javascript,Node.js,Regex,我不确定问题出在哪里,但在Javascript(Nodejs、Chrome控制台、Firefox控制台)中运行for loop内的exec()会产生错误的结果。据我所知,exec()是一个同步方法,在同步循环内调用,该循环应产生预期的输出 const FILTER_REGEX = /(\w+)\s+(below|under|lesser than|lower than|above|over|more than|higher than|greater than|equals|equal to|sa

我不确定问题出在哪里,但在Javascript(Nodejs、Chrome控制台、Firefox控制台)中运行for loop内的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}`);
}
这应该可以做到

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}`);
}
const FILTER_REGEX=/(\w+)\s+(低于|低于|低于|高于|超过|高于|大于|等于|与|>相同这应该可以做到

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}`);
}

const FILTER_REGEX=/(\w+)\s+(低于|低于|低于|高于|高于|高于|大于|等于|等同于|>|@某些性能如何重复这个问题?几乎是这样,但这个问题仍然悬而未决。问题是您的
FILTER_REGEX
是全局的,并且有一个状态(
lastIndex
属性)。如果每次运行一个新的正则表达式,输出将与预期的一样。而不是在使用
.exec
时,它将返回下一个匹配项(直到它结束并找不到更多匹配项,然后重新开始),您可以使用
RegExp.lastMatch
(MDN说它的跨浏览器兼容性很差,但我还没有看到它失败);但标准的方法是via。@CertainPerformance它是如何重复这个问题的?几乎是,但这个问题仍然存在。问题是您的
过滤器\u REGEX
是全局的,并且有一个状态(
lastIndex
属性)。如果您每次都运行一个新的正则表达式,则输出将如预期的那样。当您使用
.exec
时,它将返回下一个匹配项(直到它结束并找不到更多匹配项,然后重新开始)。您可以使用
RegExp.lastMatch
(MDN说它的跨浏览器兼容性很差,但我还没有看到它失败);但标准方式是通过。